'; resultArea.classList.add('show'); } catch (err) { errorMsg.textContent = '错误: ' + err.message; resultArea.classList.remove('show'); } } function doDecode() { errorMsg.textContent = ''; try { var s = document.getElementById('input').value.trim(); if (!s) throw new Error('请输入要解码的内容'); // 1. 收集所有 %XX var bytes = []; var i = 0; while (i < s.length) { if (s[i] === '%' && i + 2 < s.length) { var hex = s.substring(i+1, i+3); if (/^[0-9A-Fa-f]{2}$/.test(hex)) { bytes.push(parseInt(hex, 16)); i += 3; continue; } } bytes.push(s.charCodeAt(i)); i++; } // 2. UTF-8 解码 var decoded = ''; var j = 0; while (j < bytes.length) { var b1 = bytes[j]; if (b1 < 0x80) { decoded += String.fromCharCode(b1); j++; } else if (b1 >= 0xC0 && b1 < 0xE0 && j+1 < bytes.length) { decoded += String.fromCharCode(((b1 & 0x1F) << 6) | (bytes[j+1] & 0x3F)); j += 2; } else if (b1 >= 0xE0 && b1 < 0xF0 && j+2 < bytes.length) { decoded += String.fromCharCode(((b1 & 0x0F) << 12) | ((bytes[j+1] & 0x3F) << 6) | (bytes[j+2] & 0x3F)); j += 3; } else { decoded += String.fromCharCode(b1); j++; } } resultMeta.textContent = '编码长度: ' + s.length + ' 字符 · 解码后长度: ' + decoded.length; resultContent.innerHTML = '
' + decoded + '
'; resultArea.classList.add('show'); } catch (err) { errorMsg.textContent = '错误: ' + err.message; resultArea.classList.remove('show'); } } document.getElementById('btn-enc').addEventListener('click', doEncode); document.getElementById('btn-dec').addEventListener('click', doDecode); })();