HTML格式化工具

快速将非格式化或混乱的HTML代码转换为缩进清晰、结构规范的格式

输入HTML代码

格式化结果

已复制!
// 初始化行号 function updateLineNumbers() { const lines = inputCode.value.split('\n'); lineNumbers.innerHTML = lines.map((_, idx) => idx + 1).join('
'); } // 格式化HTML代码 function formatHtml() { const htmlCode = inputCode.value; if (!htmlCode.trim()) return; // 获取缩进选项 const indentSizeValue = indentSize.value; const options = { indent_size: indentSizeValue === 'tab' ? 4 : parseInt(indentSizeValue), space_in_empty_paren: true, wrap_attributes: 'force-expand-multiline', wrap_line_length: 80, unformatted: ['code', 'pre', 'em', 'strong', 'span'] }; try { // 使用js-beautify格式化HTML const formattedHtml = html_beautify(htmlCode, options); outputCode.textContent = formattedHtml; // 应用语法高亮 hljs.highlightElement(outputCode); } catch (error) { outputCode.textContent = `格式化错误: ${error.message}`; } } // 复制格式化后的代码 function copyFormattedCode() { const textToCopy = outputCode.textContent; if (!textToCopy.trim()) return; navigator.clipboard.writeText(textToCopy) .then(() => { // 显示复制成功通知 copyNotification.classList.remove('opacity-0'); setTimeout(() => { copyNotification.classList.add('opacity-0'); }, 2000); }) .catch(err => { console.error('复制失败:', err); }); } // 清空输入和输出 function clearEditor() { inputCode.value = ''; outputCode.textContent = ''; updateLineNumbers(); } // 加载示例代码 function loadSampleCode() { inputCode.value = sampleCode; updateLineNumbers(); formatHtml(); } // 切换主题 function toggleTheme() { document.documentElement.classList.toggle('dark'); if (document.documentElement.classList.contains('dark')) { lightTheme.disabled = true; darkTheme.disabled = false; localStorage.setItem('theme', 'dark'); } else { lightTheme.disabled = false; darkTheme.disabled = true; localStorage.setItem('theme', 'light'); } // 重新应用语法高亮以适应新主题 hljs.highlightElement(outputCode); } // 检查本地存储中的主题偏好 function checkThemePreference() { const savedTheme = localStorage.getItem('theme'); if (savedTheme === 'dark') { document.documentElement.classList.add('dark'); lightTheme.disabled = true; darkTheme.disabled = false; } else { document.documentElement.classList.remove('dark'); lightTheme.disabled = false; darkTheme.disabled = true; } } // 事件监听器 inputCode.addEventListener('input', () => { updateLineNumbers(); // 实时格式化 formatHtml(); }); formatBtn.addEventListener('click', formatHtml); copyBtn.addEventListener('click', copyFormattedCode); clearBtn.addEventListener('click', clearEditor); sampleCodeBtn.addEventListener('click', loadSampleCode); themeToggle.addEventListener('click', toggleTheme); indentSize.addEventListener('change', formatHtml); // 初始化 document.addEventListener('DOMContentLoaded', () => { checkThemePreference(); updateLineNumbers(); hljs.highlightElement(outputCode); // 添加动画效果 formatBtn.classList.add('animate-pulse'); setTimeout(() => { formatBtn.classList.remove('animate-pulse'); }, 1000); });