Use native JS for CSS formatting and Compression

Source: Internet
Author: User
The preface has always liked collecting special webpage effects. In many cases, CSS is compressed, which is inconvenient to view. Sometimes, to reduce the file size, it will also compress its own CSS. There are a lot of such services on the Internet, but they are not satisfactory, so I plan to do it myself... syntaxHighlighter. all ();

Preface
I have always liked to collect special webpage effects. In many cases, CSS is compressed, which is inconvenient to view. Sometimes, to reduce the file size, it will also compress its own CSS. There are a lot of such services available on the Internet, but they are not satisfactory. Therefore, we plan to write a JS to format and compress CSS.
Principle
The structure of CSS is as follows:
Selector {
Css attribute Declaration: value;
}

Therefore, CSS formatting is relatively simple, which can be roughly divided into the following steps;
1. Merge multiple spaces into one and remove line breaks.
2. Group processed strings "{"
3. traverse the group and group the parts containing "}" again "}"
4. process the grouped data by adding spaces and line breaks.
It's easy to compress CSS. Combine spaces and remove line breaks.
Format
The preceding steps are implemented step by step.
Initialization:
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 = [];
}

The parameters here are the CSS code to be formatted, the space width before the CSS attribute declaration, type (format/compression)
1. Combine multiple spaces into one and remove the line feed:
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. Group processed strings "{"
Formathtmljscss. prototype. split = function (){
Var bigqleft = this. source. split ("{");
}

3. traverse the group and group the parts containing "}" again "}"
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. process the grouped data by adding spaces and line feed www.2cto.com.
The processing here is mainly divided into taking out the CSS attribute declaration and value, and then adding spaces and line breaks:
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 ");
}
}
}

Several methods are called: trim, formatSelect, and formatStatement.
Trim: It can be seen from the name that it is to remove spaces at the beginning and end;
Formathtmljscss. prototype. trim = function (str ){
Return str. replace (/(^ \ s *) | (\ s * $)/g ,"");
}

FormatSelect: it is used to process part of the selector syntax. It is used to add spaces before ".", remove spaces before and after ", and combine multiple spaces into one:
Formathtmljscss. prototype. formatSelect = function (str ){
Return str. replace (/\./g ,".")
. Replace (/\ s +/g ,"")
. Replace (/\./g ,".")
. Replace (/\ s *, \ s */g ,",");
}

FormatStatement: refers to the syntax used to process the "css attribute Declaration: value;" part. It adds spaces to ":" and merges multiple spaces into one, remove the space after "#", remove the space before "px", and remove the space on both sides. Remove the space before:
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;
}

Call
The call part is relatively simple. for formatting, spaces and line breaks are removed and grouped for processing. For compression, spaces and line breaks are removed:
Formathtmljscss. prototype. formatcss = function (){
If (this. formatType = "compress "){
This. removeSpace ();
}
Else {
This. removeSpace ();
This. split ();
This. source = this. output. join ("");
}
}

Interface HTML code:
View Code




CSS formatting/compression



Format/compress


Indent:


  • Tab key indent2 space indentation4. Space indent



Type:

Format
Compression












Bind an event to the page element button:
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;
}
}

Demo

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 formatting/compression


 

Format/Compression
Indent:
  •  

Type:
Format  Compression


 


Author: Artwl

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

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.