這是一個簡單實用的 CSS 代碼格式化小工具,能幫助你把雜亂的樣式代碼整理成整齊易讀的形式。頁面提供「橫排」「豎排」「清空」三個操作。
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "https://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="https://www.w3.org/1999/xhtml"><head>
<title>CSS 代碼格式化工具</title>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312">
<script type="text/javascript">
function formatCSS(n){
var c = document.getElementById("abc");
var d = document.getElementById("def");
var v = c.value;
if (n==1){
d.value = v.replace(/\r\n/g,"").replace(/}/g,"}\r\n");
}
if (n==2){
d.value = v.replace(/\r\n/g,"").replace(/}/g,"}\r\n").replace(/\s*;\s*/g,";").replace(/;/g,";\r\n\t").replace(/{/g,"{\r\n\t").replace(/}/g,"\r\n}").replace(/\r\n/g,"\r\n");
}
if (n==3){
c.value = d.value = "";
}
}
</script>
</head><body onload="document.getElementById('abc').focus()">
<h1>CSS 代碼格式化工具</h1>
<textarea id="abc" cols="150" rows="20" wrap="off" title="在這裡輸入CSS代碼"></textarea>
<input value=" 橫排 " onclick="formatCSS(1)" type="button">
<input value=" 豎排 " onclick="formatCSS(2)" type="button">
<input value=" 清空 " onclick="formatCSS(3)" type="button">
<textarea id="def" cols="150" rows="20" wrap="off" title="這裡將輸出CSS代碼"></textarea>
</body></html>
實現原理很直接:透過 JavaScript 的字符串 replace 方法,用正則表達式在 }、;、{ 等關鍵符號後插入換行與縮排,從而完成格式化。「橫排」按規則塊分行,「豎排」進一步為每條聲明換行並加入 Tab 縮進,「清空」則一鍵重置兩個文本框。