您的位置:首页 > Web前端 > JavaScript

Html、Css、Js 编码规范

2016-05-18 19:02 417 查看
Css规范




前言

虽然本文档是针对CSS设计的,但是在使用各种CSS的预编译器(如less、sass、stylus等)时,适用的部分也应尽量遵循本文档的约定。


代码风格


文件编码

[建议]CSS文件使用UTF-8编码。


缩进

[强制]使用softtab(4个空格)做为一个缩进层级,不允许使用2个空格或tab字符。
示例:.selector{

margin:0;

padding:0;

}


分号

【强制】每个属性声明末尾都要加分号
示例:.selector{

margin:0;

padding:0;

}



行长度

[强制]每行不得超过120个字符,除非单行不可分割。

如url过长时不必分割

[建议]对于超长的样式,在样式值的空格处或,后换行,建议按逻辑分组。
示例:

/*不同属性值按逻辑分组*/

background:

transparenturl(aVeryVeryVeryLongUrlIsPlacedHere)

no-repeat00;


/*可重复多次的属性,每次重复一行*/

background-image:

url(aVeryVeryVeryLongUrlIsPlacedHere)

url(anotherVeryVeryVeryLongUrlIsPlacedHere);

/*类似函数的属性值可以根据函数调用的缩进进行*/

background-image:-webkit-gradient(

linear,

leftbottom,

lefttop,

color-stop(0.04,rgb(88,94,124)),

color-stop(0.52,rgb(115,123,162))

);


选择器

[强制]当一个rule包含多个
selector时,每个选择器声明必须独占一行。

示例:

/*good*/

.post,

.page,

.comment{

line-height:1.5;

}

/*bad*/

.post,.page,.comment{

line-height:1.5;

}


[强制]>、+、~选择器的两边各保留一个空格。
示例:

/*good*/

main>nav{

padding:10px;

}

label+input{

margin-left:5px;

}

input:checked~button{

background-color:#69C;

}

/*bad*/

main>nav{

padding:10px;

}

label+input{

margin-left:5px;

}

input:checked~button{

background-color:#69C;

}


[强制]属性选择器中的值必须用双引号包围。

不允许使用单引号,不允许不使用引号。

示例:

/*good*/

article[name="abc"]{

}


/*bad*/

article[name=’abc’]{

}


属性

[强制]属性定义必须另起一行。
示例:

/*good*/

.selector{

margin:0;

padding:0;

}

/*bad*/

.selector{margin:0;padding:0;}


通用


选择器

[强制]如无必要,不得为id、class选择器添加类型选择器进行限定。

样式系统从最右边的选择符开始向左进行匹配,只要当前选择符的左边还有其他选择符,样式系统就会继续向左移动,直到找到和规则匹配的元素,或者因为不匹配而退出


示例:

/*good*/

#error,

.danger-message{

font-color:#c00;

}

/*bad*/

dialog#error,p.danger-message{

font-color:#c00;

}


[建议]选择器的嵌套层级应不大于3级,位置靠后的限定条件应尽可能精确。
示例:

/*good*/

#usernameinput{}

.comment.avatar{}


/*bad*/

.page.header.login#usernameinput{}

.commentdiv*{}


属性缩写

[建议]在可以使用缩写的情况下,尽量使用属性缩写。
示例:

/*good*/

.post{

font:12px/1.5arial,sans-serif;

}

/*bad*/

.post{

font-family:arial,sans-serif;

font-size:12px;

line-height:1.5;

}


[建议]使用border/margin/padding等缩写时,应注意隐含值对实际数值的影响,确实需要设置多个方向的值时才使用缩写。

border/margin/padding等缩写会同时设置多个属性的值,容易覆盖不需要覆盖的设定。如某些方向需要继承其他声明的值,则应该分开设置。

示例:

/*centering<articleclass="page">horizontallyandhighlightfeaturedones*/

article{

margin:5px;

border:1pxsolid#999;

}

/*good*/

.page{

margin-right:auto;

margin-left:auto;

}

.featured{

border-color:#69c;

}

/*bad*/

.page{

margin:5pxauto;/*冗余*/

}

.featured{

border:1pxsolid#69c;/*冗余*/

}


属性书写顺序

[建议]同一
ruleset下的属性在书写时,应按功能进行分组,并以FormattingModel(布局方式、位置)>BoxModel(尺寸)>Typographic(文本相关)>Visual(视觉效果)的顺序书写,以提高代码的可读性。


1.FormattingModel相关属性包括:position/top/right/bottom/left/float/display/overflow等

2.BoxModel相关属性包括:border/margin/padding/width/height等

3.Typographic相关属性包括:font/line-height/text-align/word-wrap等

4.Visual相关属性包括:background/color/transition/list-style等

示例:

.sidebar{

/*formattingmodel:positioningschemes/offsets/z-indexes/display/...*/

position:absolute;

top:50px;

left:0;

overflow-x:hidden;


/*boxmodel:sizes/margins/paddings/borders/...*/

width:200px;

padding:5px;

border:1pxsolid#ddd;


/*typographic:font/aligns/textstyles/...*/

font-size:14px;

line-height:20px;


/*visual:colors/shadows/gradients/...*/

background:#f5f5f5;

color:#333;

-webkit-transition:color1s;

-moz-transition:color1s;

transition:color1s;

}


清除浮动

[建议]当元素需要撑起高度以包含内部的浮动元素时,通过对伪类设置clear或触发BFC的方式进行clearfix。尽量不使用增加空标签的方式。


!important

[建议]尽量不使用!important声明。当需要强制指定样式且不允许任何场景覆盖时,通过标签内联和!important定义样式。

仅在设计上确实不允许任何其它场景覆盖样式时,才使用内联的!important样式。通常在第三方环境的应用中使用这种方案。


z-index

[建议]将z-index进行分层,对文档流外绝对定位元素的视觉层级关系进行管理。

普通应用:1-999

悬浮菜单:1000-4999

模态窗口:5000-9999



值与单位


文本

[强制]文本内容必须用双引号包围。

文本类型的内容可能在选择器、属性值等内容中。

示例:

/*good*/

html[lang|="zh"]q:before{

font-family:"MicrosoftYaHei",sans-serif;

content:"“";

}


/*bad*/

html[lang|=zh]q:before{

font-family:'MicrosoftYaHei',sans-serif;

content:'“';

}



数值

[强制]当数值为0-1之间的小数时,省略整数部分的0。

示例:

/*good*/

panel{

opacity:.8

}

/*bad*/

panel{

opacity:0.8

}


url()

[强制]url()函数中的路径不加引号。
示例:

body{

background:url(bg.png);

}


[建议]url()函数中的绝对路径可省去协议名。
示例:

body{

background:url(//baidu.com/img/bg.png)no-repeat00;

}


长度

[强制]长度为0时须省略单位。(也只有长度单位可省)

示例:

/*good*/

body{

padding:05px;

}

/*bad*/

body{

padding:0px5px;

}


颜色

[强制]RGB颜色值必须使用十六进制记号形式#rrggbb。不允许使用rgb()。

带有alpha的颜色信息可以使用rgba()。使用rgba()时每个逗号后必须保留一个空格。

示例:

/*good*/

.success{

box-shadow:002pxrgba(0,128,0,.3);

border-color:#008000;

}

/*bad*/

.success{

box-shadow:002pxrgba(0,128,0,.3);

border-color:rgb(0,128,0);

}


[强制]颜色值可以缩写时,必须使用缩写形式。

示例:

/*good*/

.success{

background-color:#aca;

}

/*bad*/

.success{

background-color:#aaccaa;

}


[建议]颜色值中的英文字符采用小写。
示例:

/*good*/

.success{

background-color:#aca;

color:#90ee90;

}


/*bad*/

.success{

background-color:#ACA;

color:#90ee90;

}


2D位置

[强制]必须同时给出水平和垂直方向的位置。

2D位置(background-position)初始值为0%0%,但在只有一个方向的值时,另一个方向的值会被解析为center。为避免理解上的困扰,应同时给出两个方向的值。

示例:

/*good*/

body{

background-position:centertop;/*50%0%*/

}

/*bad*/

body{

background-position:top;/*50%0%*/

}


文本编排


字体族

[强制]font-family属性中的字体族名称应使用字体的英文Family
Name,其中如有空格,须放置在引号中。


字体
操作系统
FamilyName
宋体(中易宋体)
Windows
SimSun
黑体(中易黑体)
Windows
SimHei
微软雅黑
Windows
MicrosoftYaHei
微软正黑
Windows
MicrosoftJhengHei
华文黑体
Mac/iOS
STHeiti
冬青黑体
Mac/iOS
HiraginoSansGB

示例:h1{

font-family:"MicrosoftYaHei";

}


[强制]font-family按「西文字体在前、中文字体在后」、「效果佳
(质量高/更能满足需求)的字体在前、效果一般的字体在后」的顺序编写,最后必须指定一个通用字体族(serif/sans-serif)。


更详细说明可参考本文。

示例:

/*Displayaccordingtoplatform*/

.article{

font-family:Arial,sans-serif;

}

/*Specificformostplatforms*/

h1{

font-family:"HelveticaNeue",Arial,"HiraginoSansGB","WenQuanYiMicroHei","MicrosoftYaHei",sans-serif;

}


字号

[强制]需要在Windows平台显示的中文内容,其字号应不小于12px。

由于Windows的字体渲染机制,小于12px的文字显示效果极差、难以辨认。



行高

[建议]line-height在定义文本段落时,应使用数值。

将line-height设置为数值,浏览器会基于当前元素设置的font-size进行再次计算。在不同字号的文本段落组合中,能达到较为舒适的行间间隔效果,避免在每个设置了font-size都需要设置line-height。

当line-height用于控制垂直居中时,还是应该设置成与容器高度一致。


变换与动画

[强制]使用transition时应指定transition-property。
示例:

/*good*/

.box{

transition:color1s,border-color1s;

}

/*bad*/

.box{

transition:all1s;

}


响应式

[强制]MediaQuery如果有多个逗号分隔的条件时,应将每个条件放在单独一行中。
示例:

@media

(-webkit-min-device-pixel-ratio:2),/*Webkit-basedbrowsers*/

(min--moz-device-pixel-ratio:2),/*OlderFirefoxbrowsers(priortoFirefox16)*/

(min-resolution:2dppx),/*Thestandardway*/

(min-resolution:192dpi){/*dppxfallback*/

/*Retina-specificstuffhere*/

}


兼容性


属性前缀

[强制]带私有前缀的属性由长到短排列,按冒号位置对齐。

标准属性放在最后,按冒号对齐方便阅读,也便于在编辑器内进行多行编辑。

示例:

.box{

-webkit-box-sizing:border-box;

-moz-box-sizing:border-box;

box-sizing:border-box;

}


Hack

[建议]需要添加hack时应尽可能考虑是否可以采用其他方式解决。

如果能通过合理的HTML结构或使用其他的CSS定义达到理想的样式,则不应该使用hack手段解决问题。通常hack会导致维护成本的增加。

[建议]尽量使用选择器hack处理兼容性,而非属性
hack。


尽量使用符合CSS语法的selectorhack,可以避免一些第三方库无法识别hack语法的问题。

示例:

/*IE7*/

*:first-child+html#header{

margin-top:3px;

padding:5px;

}

/*IE6*/

*html#header{

margin-top:5px;

padding:4px;

}


[建议]尽量使用简单的属性hack。

示例:

.box{

_display:inline;/*fixdoublemargin*/

float:left;

margin-left:20px;

}

.container{

overflow:hidden;

*zoom:1;/*triggeringhasLayout*/

}


Expression

[强制]禁止使用Expression。


sass中的嵌套

【建议】避免非必要的嵌套

虽然你可以使用嵌套,但是并不意味着应该使用嵌套。只有在必须将样式限制在父元素内(也就是后代选择器),并且存在多个需要嵌套的元素时才使用嵌套。

Html规范


语法

[强制]

对于属性的定义,确保全部使用双引号,绝不要使用单引号。

不要在自闭合(self-closing)元素的尾部添加斜线

不要省略可选的结束标签(closingtag)(例如,</li>或</body>)。

<!DOCTYPEhtml>

<html>

<head>[/code]
<title>
Pagetitle
</title>[/code]
</head>[/code]
<body>[/code]
<imgsrc="images/company-logo.png"alt="Company">[/code]
<h1class="hello-world">
Hello,world!
</h1>[/code]
</body>[/code]
</html>


doctype

[建议]为每个HTML页面的第一行添加standard
mode的声明,这样能够确保在每个浏览器中拥有一致的展现。


<!DOCTYPEhtml>

<html>

<head>[/code]
</head>[/code]
<html>


引入CSS和JavaScript文件

[建议]在引入CSS和JavaScript文件时不需要指定type属性,因为text/css和text/javascript分别是它们的默认值。


属性顺序

[建议]按照以下给出的顺序依次排列,确保代码的易读性。

class用于标识高度可复用组件,因此应该排在首位。id用于标识具体组件,应当减少使用,因此排在第二位。

class

id
,
name

data-*

src
,
for
,
type
,
href

title
,
alt

aria-*
,
role


例如:

<aclass="..."id="..."data-modal="toggle"href="#">[code]Examplelink
</a>[/code]


布尔属性

【建议】布尔型属性可以在声明时不赋值

例如:
<inputtype="text"disabled>

<inputtype="checkbox"value="1"checked>



层级嵌套

【建议】减少标签层级嵌套,不宜超过4层

语义性

【建议】减少非语义化标签的使用,如div,span

工具验证:w3validator

Js规范


对象

[强制]使用直接量创建对象。
//bad

varitem=newObject();


//good

varitem={};



[强制]不要使用保留字作为键名

在IE8有问题,详情可参考。
//bad

varsuperman={

default:{clark:'kent'},

private:true

};

//good

varsuperman={

defaults:{clark:'kent'},

hidden:true

};


数组

[强制]使用直接量创建数组。
//bad

varitems=newArray();

//good

varitems=[];


[强制]向数组增加元素时使用Array.push来替代直接赋值。
varsomeStack=[];


//bad

someStack[someStack.length]='abracadabra';

//good

someStack.push('abracadabra');


字符串

[强制]使用单引号''包裹字符串。
//bad

varname="BobParr";

//good

varname='BobParr';

//bad

varfullName="Bob"+this.lastName;

//good

varfullName='Bob'+this.lastName;


[建议]多行字符的字符串应该使用连接符写成多行。
//bad

varerrorMessage='ThisisasuperlongerrorthatwasthrownbecauseofBatman.WhenyoustoptothinkabouthowBatmanhadanythingtodowiththis,youwouldgetnowherefast.';


//good

varerrorMessage='Thisisasuperlongerrorthatwasthrownbecause'+

'ofBatman.WhenyoustoptothinkabouthowBatmanhadanythingtodo'+

'withthis,youwouldgetnowherefast.';


[建议]程序化生成的字符串使用Array.join连接而不是使用连接符。

尤其是IE下,具体原因参考链接:jsPerf.
varitems;varmessages;varlength;vari;


messages=[{

state:'success',

message:'Thisoneworked.'

},{

state:'success',

message:'Thisoneworkedaswell.'

},{

state:'error',

message:'Thisonedidnotwork.'

}];


length=messages.length;

//bad

functioninbox(messages){

items='<ul>';


for(i=0;i<length;i++){

items+='<li>'+messages[i].message+'</li>';

}


returnitems+'</ul>';

}

//good

functioninbox(messages){

items=[];


for(i=0;i<length;i++){

//usedirectassignmentinthiscasebecausewe'remicro-optimizing.

items[i]='<li>'+messages[i].message+'</li>';

}


return'<ul>'+items.join('')+'</ul>';

}


函数

【强制】不要在一个非函数代码块(if、while等)中声明一个函数,把函数赋给一个变量。
//bad

if(currentUser){

functiontest(){

console.log('Nope.');

}

}

//good

vartest;if(currentUser){

test=functiontest(){

console.log('Yup.');

};

}


【强制】不要把参数命名为arguments。

因为会取代函数作用域内的arguments对象。
//bad

functionnope(name,options,arguments){

//...stuff...

}

//good

functionyup(name,options,args){

//...stuff...

}


变量

[建议]避免全局变量的使用。


常量

【建议】大写加下划线的方式

Eg:
NAMES_LIKE_THIS



比较运算符&等号

[建议]使用===和!==而不是==和!=.

1.对象被计算为true

2.Undefined被计算为false

3.Null被计算为false

4.布尔值被计算为布尔的值

5.数字如果是+0、-0或NaN被计算为false,否则为true

6.字符串如果是空字符串''被计算为false,否则为true

[建议]使用快捷方式

//bad

if(name!==''){

//...stuff...

}

//good

if(name){

//...stuff...

}

//bad

if(collection.length>0){

//...stuff...

}

//good

if(collection.length){

//...stuff...

}



【建议】大括号包裹所有的多行代码块。
//bad

if(test)

returnfalse;

//good

if(test)returnfalse;

//good

if(test){

returnfalse;

}



如果通过
if
else
使用多行代码块,把
else
放在
if
代码块关闭括号的同一行。

//badif(test){

thing1();

thing2();

}else{

thing3();

}

//goodif(test){

thing1();

thing2();

}else{

thing3();

}



注释

【建议】给注释增加FIXME或TODO的前缀可以帮助其他开发者快速了解这是一个需要复查的问题,或是还未完成的功能。使用//FIXME:标注问题。

functionCalculator(){


//FIXME:shouldn'tuseaglobalhere

total=0;


returnthis;

}

functionCalculator(){


//TODO:totalshouldbeconfigurablebyanoptionsparam

this.total=0;


returnthis;

}




类型转换

【建议】在语句开始时执行类型转换。

字符串:
//bad

vartotalScore=this.reviewScore+'';

//good

vartotalScore=''+this.reviewScore;

//bad

vartotalScore=''+this.reviewScore+'totalscore';

//good

vartotalScore=this.reviewScore+'totalscore';


使用parseInt转换数字时总是带上类型转换的基数:
varinputValue='4';

//bad

varval=newNumber(inputValue);

//bad

varval=+inputValue;

//bad

varval=inputValue>>0;

//bad

varval=parseInt(inputValue);

//good

varval=Number(inputValue);

//good

varval=parseInt(inputValue,10);


布尔:
varage=0;

//bad

varhasAge=newBoolean(age);

//good

varhasAge=Boolean(age);

//good

varhasAge=!!age;



命名规则

【建议】避免单字母命名。命名应具备描述性。
//bad

functionq(){

//...stuff...

}

//good

functionquery(){

//..stuff..

}


【强制】使用驼峰式命名对象、函数和实例。
//bad

varOBJEcttsssss={};

varthis_is_my_object={};

varo={};

functionc(){}

//good

varthisIsMyObject={};

functionthisIsMyFunction(){}


【强制】使用下划线_开头命名私有属性。
//bad

this.__firstName__='Panda';

this.firstName_='Panda';


//good

this._firstName='Panda';


【建议】使用_this保存this的引用。

//good

function(){

var_this=this;

returnfunction(){

console.log(_this);

};

}


【建议】文件名和模块名相同
module.exports=CheckBox;

//insomeotherfile

//bad

varCheckBox=require('./checkBox');

//bad

varCheckBox=require('./check_box');

//good

varCheckBox=require('./CheckBox');



jQuery

【强制】使用$作为存储jQuery对象的变量名前缀。

//bad

varsidebar=$('.sidebar');

//good

var$sidebar=$('.sidebar');


[强制]缓存dom查询。
//bad

functionsetSidebar(){

$('.sidebar').hide();


//...stuff...


$('.sidebar').css({

'background-color':'pink'

});

}

//good

functionsetSidebar(){

var$sidebar=$('.sidebar');

$sidebar.hide();


//...stuff...


$sidebar.css({

'background-color':'pink'

});

}


参考:
https://github.com/fex-team/styleguide
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: