站长实用工具css压缩与格式化html单页工具

可以本地使用(.html格式),不依赖服务器

html 复制代码
<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>CSS压缩工具</title>
<style>
*{box-sizing:border-box;margin:0;padding:0;font-family:Arial,sans-serif;}
 body{display:flex;justify-content:center;align-items:center;height:100vh;background-color:#f4f4f9;}
 .container{width:90%;min-width:600px;text-align:center;}
 h1{margin-bottom:20px;color:#333;}
 textarea{width:100%;height:228px;margin:10px 0;padding:10px;font-size:14px;line-height:1.4;resize:vertical;border:1px solid #ccc;border-radius:5px;}
 button{padding:10px 20px;font-size:16px;cursor:pointer;background-color:#4CAF50;color:#fff;border:none;border-radius:5px;transition:background-color 0.3s ease;}
 button:hover{background-color:#45a049;} 
</style>
</head>
<body>
    <div class="container">
        <h1>CSS 压缩工具</h1>
        <textarea id="input-css" placeholder="待处理的CSS代码"></textarea>
        <button id="compress-button">压缩CSS</button>
        <button id="format-button">格式化CSS</button>
        <textarea id="output-css" placeholder="处理(压缩/格式化)后的代码" readonly></textarea>
    </div>    
<script>
document.getElementById('compress-button').addEventListener('click', function() {
    const inputCss = document.getElementById('input-css').value;
    let compressedCss = inputCss
        // 移除注释
        .replace(/\/\*[\s\S]*?\*\//g, '')
        // 移除多余空白和换行
        .replace(/\s*{\s*/g, '{')
        .replace(/\s*}\s*/g, '}\n')
        .replace(/\s*;\s*/g, ';')
        .replace(/\s*:\s*/g, ':')
        .replace(/\s*,\s*/g, ',')
        .replace(/\s+/g, ' ')
        // 将每个选择器块独立一行
        .replace(/}(?!\s*$)/g, '}\n');
    document.getElementById('output-css').value = compressedCss;
});
document.getElementById('format-button').addEventListener('click', function() {
    const inputCss = document.getElementById('input-css').value;
    let formattedCss = inputCss
        // 移除多余的空格符号
        .replace(/\s*{\s*/g, ' {\n\t') // {后加换行和缩进
        .replace(/;\s*/g, ';\n\t')     // 每个属性后换行并缩进
        .replace(/\s*}\s*/g, '\n}\n')  // }后加换行
        // 清除多余的缩进和换行符
        .replace(/\n\t\n/g, '\n') 
        .replace(/\t}/g, '}');         // 去掉多余的缩进符号
    document.getElementById('output-css').value = formattedCss;
});
</script>
</body>
</html>
相关推荐
浪九天42 分钟前
Vue 不同大版本与 Node.js 版本匹配的详细参数
前端·vue.js·node.js
qianmoQ1 小时前
第五章:工程化实践 - 第三节 - Tailwind CSS 大型项目最佳实践
前端·css
椰果uu1 小时前
前端八股万文总结——JS+ES6
前端·javascript·es6
微wx笑2 小时前
chrome扩展程序如何实现国际化
前端·chrome
~废弃回忆 �༄2 小时前
CSS中伪类选择器
前端·javascript·css·css中伪类选择器
CUIYD_19892 小时前
Chrome 浏览器(版本号49之后)‌解决跨域问题
前端·chrome
IT、木易2 小时前
跟着AI学vue第五章
前端·javascript·vue.js
薛定谔的猫-菜鸟程序员2 小时前
Vue 2全屏滚动动画实战:结合fullpage-vue与animate.css打造炫酷H5页面
前端·css·vue.js
春天姐姐3 小时前
vue3项目开发总结
前端·vue.js·git
谢尔登3 小时前
【React】React 性能优化
前端·react.js·性能优化