站长实用工具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>
相关推荐
小马_xiaoen7 分钟前
Proxy 与 Reflect 从入门到实战:ES6 元编程核心特性详解
前端·javascript·ecmascript·es6
hoiii18717 分钟前
MATLAB SGM(半全局匹配)算法实现
前端·算法·matlab
会编程的土豆1 小时前
新手前端小细节
前端·css·html·项目
广州华水科技2 小时前
单北斗GNSS在桥梁形变监测中的应用与技术进展分析
前端
我讲个笑话你可别哭啊2 小时前
鸿蒙ArkTS快速入门
前端·ts·arkts·鸿蒙·方舟开发框架
CherryLee_12102 小时前
基于poplar-annotation前端插件封装文本标注组件及使用
前端·文本标注
特立独行的猫a2 小时前
C++轻量级Web框架介绍与对比:Crow与httplib
开发语言·前端·c++·crow·httplib
周航宇JoeZhou2 小时前
JB2-7-HTML
java·前端·容器·html·h5·标签·表单
代码小库2 小时前
【课程作业必备】Web开发技术HTML静态网站模板 - 校园动漫社团主题完整源码
前端·html
云计算DevOps-韩老师2 小时前
HTML 中的行级元素(inline)、块级元素(block)、行内块元素(inline-block)
html