用原生JS進行CSS格式化和壓縮

來源:互聯網
上載者:User

前言
一直比較喜歡收集網頁特效,很多時候都會遇到CSS被壓縮過的情況,這時查看起來就會非常不方便,有時為了減少檔案大小,也會對自己的CSS進行壓縮,網上提供這樣服務的很多,但都不盡如人意,因此打算自己動手寫一個JS來進行CSS的格式化和壓縮
原理
CSS的結構如下:
選取器{
  css屬性聲明:值;
}

所以對CSS格式化也就比較簡單,大致分為以下幾步;
1、把多個空格合并成一個,去掉換行
2、對處理後的字串按"{"進行分組
3、遍曆分組,對含有"}"的部分再次以"}"進行分組
4、對分組後的資料進行處理,主要是加上空格和換行
對CSS壓縮就比較簡單了,把空格合并,去掉換行就可以了
格式化
下面分步對以上步驟進行實現。
初始化:
function formathtmljscss(source, spaceWidth, formatType) {
    this.source = source;
    this.spaceStr = "    ";
    if (!isNaN(spaceWidth)) {
        if (spaceWidth > 1) {
            this.spaceStr = "";
            for (var i = 0; i < spaceWidth; i++) {
                this.spaceStr += " ";
            }
        }
        else {
            this.spaceStr = "\t";
        }
    }
    this.formatType = formatType;
    this.output = [];
}

這裡幾個參數分別是要格式化的CSS代碼、CSS屬性聲明前空格寬度,類型(格式化/壓縮)
1、把多個空格合并成一個,去掉換行:
formathtmljscss.prototype.removeSpace = function () {
    this.source = this.source.replace(/\s+|\n/g, " ")
        .replace(/\s*{\s*/g, "{")
        .replace(/\s*}\s*/g, "}")
        .replace(/\s*:\s*/g, ":")
        .replace(/\s*;\s*/g, ";");
}

2、對處理後的字串按"{"進行分組
formathtmljscss.prototype.split = function () {
    var bigqleft = this.source.split("{");
}

3、遍曆分組,對含有"}"的部分再次以"}"進行分組
formathtmljscss.prototype.split = function () {
    var bigqleft = this.source.split("{");
    var bigqright;
    for (var i = 0; i < bigqleft.length; i++) {
        if (bigqleft[i].indexOf("}") != -1) {
            bigqright = bigqleft[i].split("}");
        }
        else {
          
        }
    }
}

4、對分組後的資料進行處理,主要是加上空格和換行www.2cto.com
這裡的處理主要分為,把CSS屬性聲明和值部分取出來,然後加上空格和換行:
formathtmljscss.prototype.split = function () {
    var bigqleft = this.source.split("{");
    var bigqright;
    for (var i = 0; i < bigqleft.length; i++) {
        if (bigqleft[i].indexOf("}") != -1) {
            bigqright = bigqleft[i].split("}");
            var pv = bigqright[0].split(";");
            for (var j = 0; j < pv.length; j++) {
                pv[j] = this.formatStatement(this.trim(pv[j]),true);
                if (pv[j].length > 0) {
                    this.output.push(this.spaceStr + pv[j] + ";\n");
                }
            }
            this.output.push("}\n");
            bigqright[1] = this.trim(this.formatSelect(bigqright[1]));
            if (bigqright[1].length > 0) {
                this.output.push(bigqright[1], " {\n");
            }
        }
        else {
            this.output.push(this.trim(this.formatSelect(bigqleft[i])), " {\n");
        }
    }
}

這裡調用了幾個方法:trim、formatSelect、formatStatement,下面一一說明。
trim:從命名就可以看出是去除首尾空格;
formathtmljscss.prototype.trim = function (str) {
    return str.replace(/(^\s*)|(\s*$)/g, "");
}

formatSelect:是處理選取器部分文法,做法就是給"."前面加上空格,把","前後的空格去掉,把多個空格合并為一個:
formathtmljscss.prototype.formatSelect = function (str) {
    return str.replace(/\./g, " .")
        .replace(/\s+/g, " ")
        .replace(/\. /g, ".")
        .replace(/\s*,\s*/g, ",");
}

formatStatement:是處理“css屬性聲明:值;”部分的文法,做法就是給":"後面加上空格,把多個空格合并為一個,去掉“#”後面的空格,去掉"px"前面的空格,去掉"-"兩邊的空格,去掉":"前面的空格:
formathtmljscss.prototype.formatStatement = function (str, autoCorrect) {
    str = str.replace(/:/g, " : ")
        .replace(/\s+/g, " ")
        .replace("# ", "#")
        .replace(/\s*px/ig, "px")
        .replace(/\s*-\s*/g, "-")
        .replace(/\s*:/g, ":");

    return str;
}

調用
調用部分比較簡單,對于格式化來說就是去掉空格和換行,然後分組處理,對於壓縮來說就是去掉空格和換行:
formathtmljscss.prototype.formatcss = function () {
    if (this.formatType == "compress") {
        this.removeSpace();
    }
    else {
        this.removeSpace();
        this.split();
        this.source = this.output.join("");
    }
}

介面HTML代碼:
  View Code
<div id="content">
        <div class="container">
            <div class="box">
                <div class="main">
                    <h2>CSS格式化/壓縮</h2>
                    <div id="blurb">
                        <fieldset id="options">
                            <button id="submit">
                                <span>格式化 / 壓縮&nbsp;&nbsp;<img alt="格式化" src="/images/29.png"/></span>
                            </button><br/>
                            <span>縮排:</span>
                            <ul>
                                <li>
                                    <select name="tabsize" id="tabsize">
                                        <option value="1">tab鍵縮排</option>
                                        <option value="2">2空格縮排</option>
                                        <option selected="selected" value="4">4空格縮排</option>
                                    </select>
                                </li>
                            </ul><br />
                            <span>類型:</span><br />
                            <input type="radio" name="format_type" value="format" checked="checked" id="format_format" /><label for="format_format">格式化</label>
                            <input type="radio" name="format_type" value="compress" id="format_compress" /><label for="format_compress">壓縮</label>
                        </fieldset>
                    </div>
                    <div id="beauty">
                        <fieldset id="textarea-wrap">
                            <textarea rows="20" cols="40" id="source"></textarea>
                        </fieldset>
                    </div>
                </div>
            </div>
        </div>
    </div>

跟頁面元素按鈕綁定事件:
  View Code
window.onload = function () {
    var submitBtn = document.getElementById("submit");
    var tabsize = document.getElementById("tabsize");
    var sourceCon = document.getElementById("source");
    var size = 4;
    var formatType = "format";
    submitBtn.onclick = function () {
        var radios = document.getElementsByName("format_type");
        for (i = 0; i < radios.length; i++) {
            if (radios[i].checked) {
                formatType = radios[i].value;
                break;
            }
        }
        var format = new formathtmljscss(sourceCon.value, size, formatType);
        format.formatcss();
        sourceCon.value = format.source;
    }
    tabsize.onchange = function () {
        size = this.options[this.options.selectedIndex].value;
        submitBtn.click();
        return false;
    }
}

示範

 html,body{color:#000;background:#FFF;}body,div,dl,dt,dd,ul,ol,li,h1,h2,h3,h4,h5,h6,pre,code,form,fieldset,legend,input,button,textarea,p,blockquote,th,td{
margin:0;padding:0;
}table{border-collapse:collapse;
border-spacing:0;
}fieldset,img{border:0;
}address,caption,cite,code,dfn,em,strong,th,var,optgroup{font-style:inherit;
font-weight:inherit;
}del,ins{
text-decoration:none;
}li{list-style:none;
}caption,th{
text-align:left;
}h1,h2,h3,h4,h5,h6{
font-size:100%;
font-weight:normal;
}q:before,q:after{
content:'';
}abbr,acronym{
border:0;
font-variant:normal;
}sup{
vertical-align:baseline;
}sub{
vertical-align:baseline;
}legend
{color:#000;
}input,button,textarea,select,optgroup,option{
font-family:inherit;
font-size:inherit;
font-style:inherit;
font-weight:inherit;
}input,button,textarea,select{
*font-size:100%;
}.clear{
clear:both;
}input::-moz-focus-inner{
border: 0;
padding: 0;

CSS格式化/壓縮


 

格式化/ 壓縮  
縮排:
  •  

類型:
格式化  壓縮


 

 

  
作者:Artwl   

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.