最佳原则

坚持制定好的代码规范。

无论团队人数多少,代码应该同出一门。

项目命名

全部采用小写方式, 以下划线分隔。

例:my_project_name

目录命名

参照项目命名规则;

有复数结构时,要采用复数命名法。

例:scripts, styles, images, data_models

JS文件命名

参照项目命名规则。

例:account_model.js

HTML文件命名

参照项目命名规则。

例:error_report.html

语法

  • 缩进使用soft tab(4个空格);
  • 嵌套的节点应该缩进;
  • 在属性上,使用双引号,不要使用单引号;
  • 属性名全小写,用中划线做分隔符;
  • 不要在自动闭合标签结尾处使用斜线(HTML5 规范指出他们是可选的);
  • 不要忽略可选的关闭标签,例:</li> 和</body>
  • HTML5 doctype

    在页面开头使用这个简单地doctype来启用标准模式,使其在每个浏览器中尽可能一致的展现;

    虽然doctype不区分大小写,但是按照惯例,doctype大写

    1. <!DOCTYPE html>
  • lang属性

    根据HTML5规范:

    应在html标签上加上lang属性。这会给语音工具和翻译工具帮助,告诉它们应当怎么去发音和翻译。

    更多关于 lang 属性的说明在这里

    在sitepoint上可以查到语言列表

    但sitepoint只是给出了语言的大类,例如中文只给出了zh,但是没有区分香港,台湾,大陆。而微软给出了一份更加详细的语言列表,其中细分了zh-cn, zh-hk, zh-tw。

    1. <!DOCTYPE html>
    2. <html lang="en-us">
    3. ...
    4. </html>
  • 字符编码

    通过声明一个明确的字符编码,让浏览器轻松、快速的确定适合网页内容的渲染方式,通常指定为'UTF-8'。

  • IE兼容模式

    用 <meta> 标签可以指定页面应该用什么版本的IE来渲染;不同doctype在不同浏览器下会触发不同的渲染模式(这篇文章总结的很到位)。

    1. <!DOCTYPE html>
    2. <html>
    3. <head>
    4. <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    5. </head>
    6. ...
    7. </html>
  • 引入CSS, JS

    根据HTML5规范, 通常在引入CSS和JS时不需要指明type,因为 text/css 和 text/javascript 分别是他们的默认值。

    1. <!-- External CSS -->
    2. <link rel="stylesheet" href="code_guide.css">
    3. <!-- In-document CSS -->
    4. <style>
    5. ...
    6. </style>
    7. <!-- External JS -->
    8. <script src="code_guide.js"></script>
    9. <!-- In-document JS -->
    10. <script>
    11. ...
    12. </script>
  • 属性顺序

    属性应该按照特定的顺序出现以保证易读性;

    • class
    • id
    • name
    • data-*
    • srcfortypehrefvalue , max-lengthmax,minpattern
    • placeholdertitlealt
    • aria-*role
    • requiredreadonlydisabled

    class是为高可复用组件设计的,所以应处在第一位;

    id更加具体且应该尽量少使用,所以将它放在第二位。

    1. <a class="..." id="..." data-modal="toggle" href="#">Example link</a>
    2. <input class="form-control" type="text">
    3. <img src="..." alt="...">
  • boolean属性

    boolean属性指不需要声明取值的属性,XHTML需要每个属性声明取值,但是HTML5并不需要;

  • boolean属性的存在表示取值为true,不存在则表示取值为false。
    1. <input type="text" disabled>
    2. <input type="checkbox" value="1" checked>
    3. <select>
    4. <option value="1" selected>1</option>
    5. </select>
  • JS生成标签

    在JS文件中生成标签让内容变得更难查找,更难编辑,性能更差。应该尽量避免这种情况的出现。

  • 减少标签数量

    在编写HTML代码时,需要尽量避免多余的父节点;

    很多时候,需要通过迭代和重构来使HTML变得更少。

    1. <!-- Not well -->
    2. <span class="avatar">
    3. <img src="...">
    4. </span>
    5. <!-- Better -->
    6. <img class="avatar" src="...">
  • 实用高于完美

    尽量遵循HTML标准和语义,但是不应该以浪费实用性作为代价;

    任何时候都要用尽量小的复杂度和尽量少的标签来解决问题。

  • CSS, SCSS

  • 缩进

    使用soft tab(4个空格)。

    1. .element {
    2. position: absolute;
    3. top: 10px;
    4. left: 10px;
    5. border-radius: 10px;
    6. width: 50px;
    7. height: 50px;
    8. }
  • 分号

    每个属性声明末尾都要加分号。

    1. .element {
    2. width: 20px;
    3. height: 20px;
    4. background-color: red;
    5. }
  • 空格

    以下几种情况不需要空格:

    • 属性名后
    • 多个规则的分隔符','前
    • !important '!'后
    • 属性值中'('后和')'前
    • 行末不要有多余的空格

    以下几种情况需要空格:

    • 属性值前
    • 选择器'>', '+', '~'前后
    • '{'前
    • !important '!'前
    • @else 前后
    • 属性值中的','后

注释'/*'后和'*/'前

  1. /* not good */
  2. .element {
  3. color :red! important;
  4. background-color: rgba(0,0,0,.5);
  5. }
  6. /* good */
  7. .element {
  8. color: red !important;
  9. background-color: rgba(0, 0, 0, .5);
  10. }
  11. /* not good */
  12. .element ,
  13. .dialog{
  14. ...
  15. }
  16. /* good */
  17. .element,
  18. .dialog {
  19. }
  20. /* not good */
  21. .element>.dialog{
  22. ...
  23. }
  24. /* good */
  25. .element > .dialog{
  26. ...
  27. }
  28. /* not good */
  29. .element{
  30. ...
  31. }
  32. /* good */
  33. .element {
  34. ...
  35. }
  36. /* not good */
  37. @if{
  38. ...
  39. }@else{
  40. ...
  41. }
  42. /* good */
  43. @if {
  44. ...
  45. } @else {
  46. ...
  47. }

空行

以下几种情况需要空行:

    • 文件最后保留一个空行
    • '}'后最好跟一个空行,包括scss中嵌套的规则
    • 属性之间需要适当的空行,具体见属性声明顺序
      1. /* not good */
      2. .element {
      3. ...
      4. }
      5. .dialog {
      6. color: red;
      7. &:after {
      8. ...
      9. }
      10. }
      11. /* good */
      12. .element {
      13. ...
      14. }
      15. .dialog {
      16. color: red;
      17. &:after {
      18. ...
      19. }
      20. }

换行

以下几种情况不需要换行:

  • '{'前

以下几种情况需要换行:

      • '{'后和'}'前
      • 每个属性独占一行
      • 多个规则的分隔符','后
        1. /* not good */
        2. .element
        3. {color: red; background-color: black;}
        4. /* good */
        5. .element {
        6. color: red;
        7. background-color: black;
        8. }
        9. /* not good */
        10. .element, .dialog {
        11. ...
        12. }
        13. /* good */
        14. .element,
        15. .dialog {
        16. ...
        17. }

注释

注释统一用'/* */'(scss中也不要用'//'),具体参照右边的写法;

缩进与下一行代码保持一致;

可位于一个代码行的末尾,与代码间隔一个空格。

          1. /* Modal header */
          2. .modal-header {
          3. ...
          4. }
          5. /*
          6. * Modal header
          7. */
          8. .modal-header {
          9. ...
          10. }
          11. .modal-header {
          12. /* 50px */
          13. width: 50px;
          14. color: red; /* color red */
          15. }
  • 引号

    最外层统一使用双引号;

    url的内容要用引号;

    属性选择器中的属性值需要引号。

          1. .element:after {
          2. content: "";
          3. background-image: url("logo.png");
          4. }
          5. li[data-type="single"] {
          6. ...
          7. }
    • 命名

        • 类名使用小写字母,以中划线分隔
        • id采用驼峰式命名
        • scss中的变量、函数、混合、placeholder采用驼峰式命名
          1. /* class */
          2. .element-content {
          3. ...
          4. }
          5. /* id */
          6. #myDialog {
          7. ...
          8. }
          9. /* 变量 */
          10. $colorBlack: #000;
          11. /* 函数 */
          12. @function pxToRem($px) {
          13. ...
          14. }
          15. /* 混合 */
          16. @mixin centerBlock {
          17. ...
          18. }
          19. /* placeholder */
          20. %myDialog {
          21. ...
          22. }

属性声明顺序

相关的属性声明按下边的顺序做分组处理,组之间需要有一个空行。

            1. // 下面是推荐的属性的顺序
            2. [
            3. [
            4. "display",
            5. "visibility",
            6. "float",
            7. "clear",
            8. "overflow",
            9. "overflow-x",
            10. "overflow-y",
            11. "clip",
            12. "zoom"
            13. ],
            14. [
            15. "table-layout",
            16. "empty-cells",
            17. "caption-side",
            18. "border-spacing",
            19. "border-collapse",
            20. "list-style",
            21. "list-style-position",
            22. "list-style-type",
            23. "list-style-image"
            24. ],
            25. [
            26. "-webkit-box-orient",
            27. "-webkit-box-direction",
            28. "-webkit-box-decoration-break",
            29. "-webkit-box-pack",
            30. "-webkit-box-align",
            31. "-webkit-box-flex"
            32. ],
            33. [
            34. "position",
            35. "top",
            36. "right",
            37. "bottom",
            38. "left",
            39. "z-index"
            40. ],
            41. [
            42. "margin",
            43. "margin-top",
            44. "margin-right",
            45. "margin-bottom",
            46. "margin-left",
            47. "-webkit-box-sizing",
            48. "-moz-box-sizing",
            49. "box-sizing",
            50. "border",
            51. "border-width",
            52. "border-style",
            53. "border-color",
            54. "border-top",
            55. "border-top-width",
            56. "border-top-style",
            57. "border-top-color",
            58. "border-right",
            59. "border-right-width",
            60. "border-right-style",
            61. "border-right-color",
            62. "border-bottom",
            63. "border-bottom-width",
            64. "border-bottom-style",
            65. "border-bottom-color",
            66. "border-left",
            67. "border-left-width",
            68. "border-left-style",
            69. "border-left-color",
            70. "-webkit-border-radius",
            71. "-moz-border-radius",
            72. "border-radius",
            73. "-webkit-border-top-left-radius",
            74. "-moz-border-radius-topleft",
            75. "border-top-left-radius",
            76. "-webkit-border-top-right-radius",
            77. "-moz-border-radius-topright",
            78. "border-top-right-radius",
            79. "-webkit-border-bottom-right-radius",
            80. "-moz-border-radius-bottomright",
            81. "border-bottom-right-radius",
            82. "-webkit-border-bottom-left-radius",
            83. "-moz-border-radius-bottomleft",
            84. "border-bottom-left-radius",
            85. "-webkit-border-image",
            86. "-moz-border-image",
            87. "-o-border-image",
            88. "border-image",
            89. "-webkit-border-image-source",
            90. "-moz-border-image-source",
            91. "-o-border-image-source",
            92. "border-image-source",
            93. "-webkit-border-image-slice",
            94. "-moz-border-image-slice",
            95. "-o-border-image-slice",
            96. "border-image-slice",
            97. "-webkit-border-image-width",
            98. "-moz-border-image-width",
            99. "-o-border-image-width",
            100. "border-image-width",
            101. "-webkit-border-image-outset",
            102. "-moz-border-image-outset",
            103. "-o-border-image-outset",
            104. "border-image-outset",
            105. "-webkit-border-image-repeat",
            106. "-moz-border-image-repeat",
            107. "-o-border-image-repeat",
            108. "border-image-repeat",
            109. "padding",
            110. "padding-top",
            111. "padding-right",
            112. "padding-bottom",
            113. "padding-left",
            114. "width",
            115. "min-width",
            116. "max-width",
            117. "height",
            118. "min-height",
            119. "max-height"
            120. ],
            121. [
            122. "font",
            123. "font-family",
            124. "font-size",
            125. "font-weight",
            126. "font-style",
            127. "font-variant",
            128. "font-size-adjust",
            129. "font-stretch",
            130. "font-effect",
            131. "font-emphasize",
            132. "font-emphasize-position",
            133. "font-emphasize-style",
            134. "font-smooth",
            135. "line-height",
            136. "text-align",
            137. "-webkit-text-align-last",
            138. "-moz-text-align-last",
            139. "-ms-text-align-last",
            140. "text-align-last",
            141. "vertical-align",
            142. "white-space",
            143. "text-decoration",
            144. "text-emphasis",
            145. "text-emphasis-color",
            146. "text-emphasis-style",
            147. "text-emphasis-position",
            148. "text-indent",
            149. "-ms-text-justify",
            150. "text-justify",
            151. "letter-spacing",
            152. "word-spacing",
            153. "-ms-writing-mode",
            154. "text-outline",
            155. "text-transform",
            156. "text-wrap",
            157. "-ms-text-overflow",
            158. "text-overflow",
            159. "text-overflow-ellipsis",
            160. "text-overflow-mode",
            161. "-ms-word-wrap",
            162. "word-wrap",
            163. "-ms-word-break",
            164. "word-break"
            165. ],
            166. [
            167. "color",
            168. "background",
            169. "filter:progid:DXImageTransform.Microsoft.AlphaImageLoader",
            170. "background-color",
            171. "background-image",
            172. "background-repeat",
            173. "background-attachment",
            174. "background-position",
            175. "-ms-background-position-x",
            176. "background-position-x",
            177. "-ms-background-position-y",
            178. "background-position-y",
            179. "-webkit-background-clip",
            180. "-moz-background-clip",
            181. "background-clip",
            182. "background-origin",
            183. "-webkit-background-size",
            184. "-moz-background-size",
            185. "-o-background-size",
            186. "background-size"
            187. ],
            188. [
            189. "outline",
            190. "outline-width",
            191. "outline-style",
            192. "outline-color",
            193. "outline-offset",
            194. "opacity",
            195. "filter:progid:DXImageTransform.Microsoft.Alpha(Opacity",
            196. "-ms-filter:\\'progid:DXImageTransform.Microsoft.Alpha",
            197. "-ms-interpolation-mode",
            198. "-webkit-box-shadow",
            199. "-moz-box-shadow",
            200. "box-shadow",
            201. "filter:progid:DXImageTransform.Microsoft.gradient",
            202. "-ms-filter:\\'progid:DXImageTransform.Microsoft.gradient",
            203. "text-shadow"
            204. ],
            205. [
            206. "-webkit-transition",
            207. "-moz-transition",
            208. "-ms-transition",
            209. "-o-transition",
            210. "transition",
            211. "-webkit-transition-delay",
            212. "-moz-transition-delay",
            213. "-ms-transition-delay",
            214. "-o-transition-delay",
            215. "transition-delay",
            216. "-webkit-transition-timing-function",
            217. "-moz-transition-timing-function",
            218. "-ms-transition-timing-function",
            219. "-o-transition-timing-function",
            220. "transition-timing-function",
            221. "-webkit-transition-duration",
            222. "-moz-transition-duration",
            223. "-ms-transition-duration",
            224. "-o-transition-duration",
            225. "transition-duration",
            226. "-webkit-transition-property",
            227. "-moz-transition-property",
            228. "-ms-transition-property",
            229. "-o-transition-property",
            230. "transition-property",
            231. "-webkit-transform",
            232. "-moz-transform",
            233. "-ms-transform",
            234. "-o-transform",
            235. "transform",
            236. "-webkit-transform-origin",
            237. "-moz-transform-origin",
            238. "-ms-transform-origin",
            239. "-o-transform-origin",
            240. "transform-origin",
            241. "-webkit-animation",
            242. "-moz-animation",
            243. "-ms-animation",
            244. "-o-animation",
            245. "animation",
            246. "-webkit-animation-name",
            247. "-moz-animation-name",
            248. "-ms-animation-name",
            249. "-o-animation-name",
            250. "animation-name",
            251. "-webkit-animation-duration",
            252. "-moz-animation-duration",
            253. "-ms-animation-duration",
            254. "-o-animation-duration",
            255. "animation-duration",
            256. "-webkit-animation-play-state",
            257. "-moz-animation-play-state",
            258. "-ms-animation-play-state",
            259. "-o-animation-play-state",
            260. "animation-play-state",
            261. "-webkit-animation-timing-function",
            262. "-moz-animation-timing-function",
            263. "-ms-animation-timing-function",
            264. "-o-animation-timing-function",
            265. "animation-timing-function",
            266. "-webkit-animation-delay",
            267. "-moz-animation-delay",
            268. "-ms-animation-delay",
            269. "-o-animation-delay",
            270. "animation-delay",
            271. "-webkit-animation-iteration-count",
            272. "-moz-animation-iteration-count",
            273. "-ms-animation-iteration-count",
            274. "-o-animation-iteration-count",
            275. "animation-iteration-count",
            276. "-webkit-animation-direction",
            277. "-moz-animation-direction",
            278. "-ms-animation-direction",
            279. "-o-animation-direction",
            280. "animation-direction"
            281. ],
            282. [
            283. "content",
            284. "quotes",
            285. "counter-reset",
            286. "counter-increment",
            287. "resize",
            288. "cursor",
            289. "-webkit-user-select",
            290. "-moz-user-select",
            291. "-ms-user-select",
            292. "user-select",
            293. "nav-index",
            294. "nav-up",
            295. "nav-right",
            296. "nav-down",
            297. "nav-left",
            298. "-moz-tab-size",
            299. "-o-tab-size",
            300. "tab-size",
            301. "-webkit-hyphens",
            302. "-moz-hyphens",
            303. "hyphens",
            304. "pointer-events"
            305. ]
            306. ]

颜色

颜色16进制用小写字母;

颜色16进制尽量用简写。

  1. /* good */
  2. .element {
  3. color: #abcdef;
  4. background-color: #012;
  5. }

属性简写

属性简写需要你非常清楚属性值的正确顺序,而且在大多数情况下并不需要设置属性简写中包含的所有值,所以建议尽量分开声明会更加清晰;

margin 和 padding 相反,需要使用简写;

常见的属性简写包括:

  • font
  • background
  • transition
  • animation
    1. /* good */
    2. .element {
    3. transition-delay: 2s;
    4. transition-timing-function: linear;
    5. transition-duration: 1s;
    6. transition-property: opacity;
    7. }

媒体查询

尽量将媒体查询的规则靠近与他们相关的规则,不要将他们一起放到一个独立的样式文件中,或者丢在文档的最底部,这样做只会让大家以后更容易忘记他们。

  1. .element {
  2. ...
  3. }
  4. .element-avatar{
  5. ...
  6. }
  7. @media (min-width: 480px) {
  8. .element {
  9. ...
  10. }
  11. .element-avatar {
  12. ...
  13. }
  14. }

SCSS相关

提交的代码中不要有 @debug

声明顺序:

  • @extend
  • 不包含 @content 的 @include
  • 包含 @content 的 @include
  • 自身属性
  • 嵌套规则

@import 引入的文件不需要开头的'_'和结尾的'.scss';

嵌套最多不能超过5层;

@extend 中使用placeholder选择器;

去掉不必要的父级引用符号'&'。

  1. /* not good */
  2. @import "_dialog.scss";
  3. /* good */
  4. @import "dialog";
  5. /* not good */
  6. .fatal {
  7. @extend .error;
  8. }
  9. /* good */
  10. .fatal {
  11. @extend %error;
  12. }
  13. /* not good */
  14. .element {
  15. & > .dialog {
  16. ...
  17. }
  18. }
  19. /* good */
  20. .element {
  21. > .dialog {
  22. ...
  23. }
  24. }

杂项

不允许有空的规则;

元素选择器用小写字母;

去掉小数点前面的0;

去掉数字中不必要的小数点和末尾的0;

属性值'0'后面不要加单位;

同个属性不同前缀的写法需要在垂直方向保持对齐,具体参照右边的写法;

无前缀的标准属性应该写在有前缀的属性后面;

不要在同个规则里出现重复的属性,如果重复的属性是连续的则没关系;

不要在一个文件里出现两个相同的规则;

用 border: 0; 代替 border: none;

选择器不要超过4层(在scss中如果超过4层应该考虑用嵌套的方式来写);

发布的代码中不要有 @import

尽量少用'*'选择器

  1. /* not good */
  2. .element {
  3. }
  4. /* not good */
  5. LI {
  6. ...
  7. }
  8. /* good */
  9. li {
  10. ...
  11. }
  12. /* not good */
  13. .element {
  14. color: rgba(0, 0, 0, 0.5);
  15. }
  16. /* good */
  17. .element {
  18. color: rgba(0, 0, 0, .5);
  19. }
  20. /* not good */
  21. .element {
  22. width: 50.0px;
  23. }
  24. /* good */
  25. .element {
  26. width: 50px;
  27. }
  28. /* not good */
  29. .element {
  30. width: 0px;
  31. }
  32. /* good */
  33. .element {
  34. width: 0;
  35. }
  36. /* not good */
  37. .element {
  38. border-radius: 3px;
  39. -webkit-border-radius: 3px;
  40. -moz-border-radius: 3px;
  41. background: linear-gradient(to bottom, #fff 0, #eee 100%);
  42. background: -webkit-linear-gradient(top, #fff 0, #eee 100%);
  43. background: -moz-linear-gradient(top, #fff 0, #eee 100%);
  44. }
  45. /* good */
  46. .element {
  47. -webkit-border-radius: 3px;
  48. -moz-border-radius: 3px;
  49. border-radius: 3px;
  50. background: -webkit-linear-gradient(top, #fff 0, #eee 100%);
  51. background: -moz-linear-gradient(top, #fff 0, #eee 100%);
  52. background: linear-gradient(to bottom, #fff 0, #eee 100%);
  53. }
  54. /* not good */
  55. .element {
  56. color: rgb(0, 0, 0);
  57. width: 50px;
  58. color: rgba(0, 0, 0, .5);
  59. }
  60. /* good */
  61. .element {
  62. color: rgb(0, 0, 0);
  63. color: rgba(0, 0, 0, .5);
  64. }

JavaScript

缩进

使用soft tab(4个空格)。

  1. var x = 1,
  2. y = 1;
  3. if (x < y) {
  4. x += 10;
  5. } else {
  6. x += 1;
  7. }

单行长度

不要超过80,但如果编辑器开启word wrap可以不考虑单行长度。

分号

以下几种情况后需加分号:

  • 变量声明
  • 表达式
  • return
  • throw
  • break
  • continue
  • do-while
    1. /* var declaration */
    2. var x = 1;
    3. /* expression statement */
    4. x++;
    5. /* do-while */
    6. do {
    7. x++;
    8. } while (x < 10);
  • 空格

    以下几种情况不需要空格:

    1. 对象的属性名后
    2. 前缀一元运算符后
    3. 后缀一元运算符前
    4. 函数调用括号前
    5. 无论是函数声明还是函数表达式,'('前不要空格
    6. 数组的'['后和']'前
    7. 对象的'{'后和'}'前
    8. 运算符'('后和')'前

    以下几种情况需要空格:

      1. 二元运算符前后
      2. 三元运算符'?:'前后
      3. 代码块'{'前
      4. 下列关键字前:elsewhilecatchfinally
      5. 下列关键字后:ifelseforwhiledo,switchcasetrycatchfinallywith,returntypeof
      6. 单行注释'//'后(若单行注释和代码同行,则'//'前也需要),多行注释'*'后
      7. 对象的属性值前
      8. for循环,分号后留有一个空格,前置条件如果有多个,逗号后留一个空格
      9. 无论是函数声明还是函数表达式,'{'前一定要有空格
      10. 函数的参数之间
    1. // not good
    2. var a = {
    3. b :1
    4. };
    5. // good
    6. var a = {
    7. b: 1
    8. };
    9. // not good
    10. ++ x;
    11. y ++;
    12. z = x?1:2;
    13. // good
    14. ++x;
    15. y++;
    16. z = x ? 1 : 2;
    17. // not good
    18. var a = [ 1, 2 ];
    19. // good
    20. var a = [1, 2];
    21. // not good
    22. var a = ( 1+2 )*3;
    23. // good
    24. var a = (1 + 2) * 3;
    25. // no space before '(', one space before '{', one space between function parameters
    26. var doSomething = function(a, b, c) {
    27. // do something
    28. };
    29. // no space before '('
    30. doSomething(item);
    31. // not good
    32. for(i=0;i<6;i++){
    33. x++;
    34. }
    35. // good
    36. for (i = 0; i < 6; i++) {
    37. x++;
    38. }

    空行

    以下几种情况需要空行:

    • 变量声明后(当变量声明在代码块的最后一行时,则无需空行)
    • 注释前(当注释在代码块的第一行时,则无需空行)
    • 代码块后(在函数调用、数组、对象中则无需空行)
    • 文件最后保留一个空行
      1. // need blank line after variable declaration
      2. var x = 1;
      3. // not need blank line when variable declaration is last expression in the current block
      4. if (x >= 1) {
      5. var y = x + 1;
      6. }
      7. var a = 2;
      8. // need blank line before line comment
      9. a++;
      10. function b() {
      11. // not need blank line when comment is first line of block
      12. return a;
      13. }
      14. // need blank line after blocks
      15. for (var i = 0; i < 2; i++) {
      16. if (true) {
      17. return false;
      18. }
      19. continue;
      20. }
      21. var obj = {
      22. foo: function() {
      23. return 1;
      24. },
      25. bar: function() {
      26. return 2;
      27. }
      28. };
      29. // not need blank line when in argument list, array, object
      30. func(
      31. 2,
      32. function() {
      33. a++;
      34. },
      35. 3
      36. );
      37. var foo = [
      38. 2,
      39. function() {
      40. a++;
      41. },
      42. 3
      43. ];
      44. var foo = {
      45. a: 2,
      46. b: function() {
      47. a++;
      48. },
      49. c: 3
      50. };
  • 换行

    换行的地方,行末必须有','或者运算符;

    以下几种情况不需要换行:

    • 下列关键字后:elsecatchfinally
    • 代码块'{'前

    以下几种情况需要换行:

    • 代码块'{'后和'}'前
    • 变量赋值后
  • 单行注释

    双斜线后,必须跟一个空格;

    缩进与下一行代码保持一致;

    可位于一个代码行的末尾,与代码间隔一个空格。

    1. if (condition) {
    2. // if you made it here, then all security checks passed
    3. allowed();
    4. }
    5. var zhangsan = 'zhangsan'; // one space after code
  • 多行注释

    最少三行, '*'后跟一个空格,具体参照右边的写法;

    建议在以下情况下使用:

    • 难于理解的代码段
    • 可能存在错误的代码段
    • 浏览器特殊的HACK代码
    • 业务逻辑强相关的代码
      1. /*
      2. * one space after '*'
      3. */
      4. var x = 1;

引号

最外层统一使用单引号。

函数

无论是函数声明还是函数表达式,'('前不要空格,但'{'前一定要有空格;

函数调用括号前不需要空格;

立即执行函数外必须包一层括号;

不要给inline function命名;

参数之间用', '分隔,注意逗号后有一个空格。

文档注释

各类标签@param, @method等请参考usejsdocJSDoc Guide

建议在以下情况下使用:

  • 所有常量
  • 所有函数
  • 所有类
    1. /**
    2. * @func
    3. * @desc 一个带参数的函数
    4. * @param {string} a - 参数a
    5. * @param {number} b=1 - 参数b默认值为1
    6. * @param {string} c=1 - 参数c有两种支持的取值</br>1—表示x</br>2—表示xx
    7. * @param {object} d - 参数d为一个对象
    8. * @param {string} d.e - 参数d的e属性
    9. * @param {string} d.f - 参数d的f属性
    10. * @param {object[]} g - 参数g为一个对象数组
    11. * @param {string} g.h - 参数g数组中一项的h属性
    12. * @param {string} g.i - 参数g数组中一项的i属性
    13. * @param {string} [j] - 参数j是一个可选参数
    14. */
    15. function foo(a, b, c, d, g, j) {
    16. ...
    17. }
    1. // no space before '(', but one space before'{'
    2. var doSomething = function(item) {
    3. // do something
    4. };
    5. function doSomething(item) {
    6. // do something
    7. }
    8. // not good
    9. doSomething (item);
    10. // good
    11. doSomething(item);
    12. // requires parentheses around immediately invoked function expressions
    13. (function() {
    14. return 1;
    15. })();
    16. // not good
    17. [1, 2].forEach(function x() {
    18. ...
    19. });
    20. // good
    21. [1, 2].forEach(function() {
    22. ...
    23. });
    24. // not good
    25. var a = [1, 2, function a() {
    26. ...
    27. }];
    28. // good
    29. var a = [1, 2, function() {
    30. ...
    31. }];
    32. // use ', ' between function parameters
    33. var doSomething = function(a, b, c) {
    34. // do something
    35. };
  • 数组、对象

    对象属性名不需要加引号;

    对象以缩进的形式书写,不要写在一行;

    数组、对象最后不要有逗号。

    1. // not good
    2. var a = {
    3. 'b': 1
    4. };
    5. var a = {b: 1};
    6. var a = {
    7. b: 1,
    8. c: 2,
    9. };
    10. // good
    11. var a = {
    12. b: 1,
    13. c: 2
    14. };
  • 括号

    下列关键字后必须有大括号(即使代码块的内容只有一行):ifelseforwhiledoswitchtry,catchfinallywith

    1. // not good
    2. if (condition)
    3. doSomething();
    4. // good
    5. if (condition) {
    6. doSomething();
    7. }
  • null

    适用场景:

    • 初始化一个将来可能被赋值为对象的变量
    • 与已经初始化的变量做比较
    • 作为一个参数为对象的函数的调用传参
    • 作为一个返回对象的函数的返回值

    不适用场景:

    • 不要用null来判断函数调用时有无传参
    • 不要与未初始化的变量做比较
  • undefined

    永远不要直接使用undefined进行变量判断;

    使用typeof和字符串'undefined'对变量进行判断。

  • jshint

    用'===', '!=='代替'==', '!=';

    for-in里一定要有hasOwnProperty的判断;

    不要在内置对象的原型上添加方法,如Array, Date;

    1. // not good
    2. if (a == 1) {
    3. a++;
    4. }
    5. // good
    6. if (a === 1) {
    7. a++;
    8. }
    9. // good
    10. for (key in obj) {
    11. if (obj.hasOwnProperty(key)) {
    12. // be sure that obj[key] belongs to the object and was not inherited
    13. console.log(obj[key]);
    14. }
    15. }
    16. // not good
    17. Array.prototype.count = function(value) {
    18. return 4;
    19. };
    20. // not good
    21. var x = 1;
    22. function test() {
    23. if (true) {
    24. var x = 0;
    25. }
    26. x += 1;
    27. }
    28. // not good
    29. function test() {
    30. console.log(x);
    31. var x = 1;
    32. }
    33. // not good
    34. new Person();
    35. // good
    36. var person = new Person();
    37. // not good
    38. delete(obj.attr);
    39. // good
    40. delete obj.attr;
    41. // not good
    42. if (a = 10) {
    43. a++;
    44. }
    45. // not good
    46. var a = [1, , , 2, 3];
    47. // not good
    48. var nums = [];
    49. for (var i = 0; i < 10; i++) {
    50. (function(i) {
    51. nums[i] = function(j) {
    52. return i + j;
    53. };
    54. }(i));
    55. }
    56. // not good
    57. var singleton = new function() {
    58. var privateVar;
    59. this.publicMethod = function() {
    60. privateVar = 1;
    61. };
    62. this.publicMethod2 = function() {
    63. privateVar = 2;
    64. };
    65. };
    1.  

    不要在内层作用域的代码里声明了变量,之后却访问到了外层作用域的同名变量;

    变量不要先使用后声明;

    不要在一句代码中单单使用构造函数,记得将其赋值给某个变量;

    不要在同个作用域下声明同名变量;

    不要在一些不需要的地方加括号,例:delete(a.b);

    不要使用未声明的变量(全局变量需要加到.jshintrc文件的globals属性里面);

    不要声明了变量却不使用;

    不要在应该做比较的地方做赋值;

    debugger不要出现在提交的代码里;

    数组中不要存在空元素;

    不要在循环内部声明函数;

    不要像这样使用构造函数,例:new function () { ... }new Object

  • sublime3插件

    1. 安装node包

      • jscs npm install jscs -g
      • jshint npm install jshint -g
      • csscomb npm install csscomb -g
      • csslint npm install csslint -g
    2. 安装gem包

      • scss-lint gem install scss_lint
    3. 安装sublime3 Package Control

      • 按下 ctrl+`
      • 复制粘贴以下代码 import urllib.request,os,hashlib; h = 'eb2297e1a458f27d836c04bb0cbaf282' + 'd0e7a3098092775ccb37ca9d6b2e4b7d'; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); by = urllib.request.urlopen( 'http://packagecontrol.io/' + pf.replace(' ', '%20')).read(); dh = hashlib.sha256(by).hexdigest(); print('Error validating download (got %s instead of %s), please try manual install' % (dh, h)) if dh != h else open(os.path.join( ipp, pf), 'wb' ).write(by)
    4. 安装sublime3插件

      • 按下 ctrl+shift+p,输入'ip'(Install Package)
      • 输入以下插件的名字,按顺序逐个进行安装:

        • EditorConfig
        • Sass
        • SublimeLinter
        • SublimeLinter-jscs
        • SublimeLinter-jshint
        • SublimeLinter-csslint
        • SublimeLinter-contrib-scss-lint
        • JSFormat
        • CSScomb
    5. 插件的配置文件

      将以下配置文件分别下载后放入项目根目录下:

    6. 编辑器及插件设置

      • sublime3 自身

        Preferences->Setting-User,增加下面两个配置:

        1. {
        2. "translate_tabs_to_spaces": true,
        3. "word_wrap": true
        4. }

        点击右下角的Spaces->Convert Indentation to Spaces可以将文件中的所有tab转换成空格

      • JSFormat

        Preferences->Package Settings->JSFormat->Setting-User,下载配置文件覆盖

        配置好后格式化的默认快捷键是 ctrl+alt+f

      • SublimeLinter

        右键->SublimeLinter->Lint Mode,有4种检查模式,建议选择 Load/save

        右键->SublimeLinter->Mark Style,建议选择 Outline

        右键->SublimeLinter->Choose Gutter Theme,建议选择 Blueberry-round

        右键->SublimeLinter->Open User Settings,将linter里面jscs的args改成 ["--verbose"],将linter里面csslint的ignore改成 "box-model,adjoining-classes,box-sizing,compatible-vendor-prefixes,gradients,text-indent,fallback-colors,star-property-hack,underscore-property-hack,bulletproof-font-face,font-faces,import,regex-selectors,universal-selector,unqualified-attributes,overqualified-elements,duplicate-background-images,floats,font-sizes,ids,important,outline-none,qualified-headings,unique-headings"

        当光标处于有错误的代码行时,详细的错误信息会显示在下面的状态栏中

        右键->SublimeLinter可以看到所有的快捷键,其中 ctrl+k, a 可以列出所有错误

      • CSScomb

        Preferences->Package Settings->CSScomb->Setting-User,下载配置文件覆盖

        配置好后格式化的默认快捷键是 ctrl+shift+c

    grunt插件

    1. 在项目中安装grunt插件

      • jscs npm install grunt-jscs --save-dev
      • jshint npm install grunt-contrib-jshint --save-dev
      • csslint npm install grunt-contrib-csslint --save-dev
      • scss-lint npm install grunt-scss-lint --save-dev
    2. 插件的配置文件

      • JSCS

        1. {
        2. options: {
        3. config: true,
        4. verbose: true
        5. },
        6. files: {
        7. src: [...]
        8. }
        9. }
      • JSHint
        1. {
        2. options: {
        3. jshintrc: true
        4. },
        5. files: {
        6. src: [...]
        7. }
        8. }
      • CSSLint
        1. {
        2. options: {
        3. csslintrc: '.csslintrc'
        4. },
        5. files: {
        6. src: [...]
        7. }
        8. }
      • SCSS-Lint
        1. {
        2. options: {
        3. config: '.scss-lint.yml'
        4. },
        5. files: {
        6. src: [...]
        7. }
        8. }

html、css、js的命名规范的更多相关文章

  1. js的命名规范

                   js的命名规范   1.驼峰命名法:首字母是小写的,接下来的字母都以大写字符开头.例如: var testValue = 0; var oneValue = 10; 2. ...

  2. html中css、div命名规范

    html中css.div命名规范 1.类class的命名规范示例 头:header 内容:content/container 尾:footer 导航:nav 侧栏:sidebar 栏目:column ...

  3. 再探CSS 中 class 命名规范

    一直以来我的CSS 的 class命名都是比较随意,有时采用驼峰式.有时采用下划线,好像没有什么统一的标准,想到什么英文单词就拿过来用,这对于自己瞎写的小项目无伤大雅,遇到冲突的问题可稍加调整改变即可 ...

  4. c#/js代码命名规范及代码规范

    常用命名 列表,lUser 数组,arrUser 字符串,strTitle 用,分割的字符串,strStatuss(多个用逗号分割的状态) C# Entity层 统一以E开始,比如EUser,EOrd ...

  5. CSS+DIV标签命名规范 搜索引擎最喜欢

    搜索引擎优化(seo)有很多工作要做,其中对代码的优化是一个很关键的步骤.为了更加符合SEO的规范,下面是目前流行的CSS+DIV的命名规则: 登录条:loginBar  标志:logo  侧栏:si ...

  6. css样式文件命名规范

    样式文件命名规范 主要 master.css, style.css, main.css 布局 layout.css 专栏 columns.css 文字 font.css 打印 print.css 主题 ...

  7. css的一些命名规范

    网页制作中规范使用DIV+CSS命名规则,可以改善优化功效特别是团队合作时候可以提供合作制作效率,具体DIV CSS命名规则CSS命名大全内容篇. 常用DIV+CSS命名大全集合,即CSS命名规则 D ...

  8. js 代码命名规范系列

    在微博上看到一个段子 “老子哪天出任ceo迎娶白富美走上人生巅峰之后,一定要雇两个长腿大熊的妹子.一个帮我想变量名字,一个帮我想git commit的message!” 可以看出 命名方方面面的问题困 ...

  9. JS 变量 命名规范 oDiv aDiv 等

    l命名规范及必要性 l可读性--能看懂 l规范性--符合规则 l匈牙利命名法 l类型前缀 类型 前缀 类型 实例 数组 a Array aItems 布尔值 b Boolean bIsComplete ...

随机推荐

  1. shell脚本操作mysql库

    shell脚本操作mysql数据库-e参数执行各种sql(指定到处编码--default-character-set=utf8 -s,去掉第一行的字段名称信息-N) 2011-05-11 18:18: ...

  2. Hadoop构成

    What Is Apache Hadoop? The Apache™ Hadoop® project develops open-source software for reliable, scala ...

  3. 第一百九十二天 how can I 坚持

    早上去中关村森林公园跑了会步,下午看了部电影<夏洛特烦恼>,感觉电影跟我看的那部小说差不多,还是挺不错的. 睡觉.

  4. CMake编译linux C++

    CMake是一个跨平台的安装(编译)工具,可以用简单的语句来描述所有平台的安装(编译过程).他能够输出各种各样的makefile或者project文件,能测试编译器所支持的C++特性,类似UNIX下的 ...

  5. STM32先设置寄存器还是先使能时钟

    http://zhidao.baidu.com/link?url=gdVNuIgLOJcV37QzbCx0IrFip5pskiPQDWpoZayr_xBEe120p4d_iWtrfDl1d4tSFaH ...

  6. LeetCode258:Add Digits

    Given a non-negative integer num, repeatedly add all its digits until the result has only one digit. ...

  7. URAL 2070 Interesting Numbers (找规律)

    题意:在[L, R]之间求:x是个素数,因子个数是素数,同时满足两个条件,或者同时不满足两个条件的数的个数. 析:很明显所有的素数,因数都是2,是素数,所以我们只要算不是素数但因子是素数的数目就好,然 ...

  8. LRESULT与wParam和lParam的问题

    在微软vc提供的头文件中有定义在winnt.h中typedef long LONG;在windef.h中typedef LONG LRESULT; 所以LRESULT就是long,也就是长整形之所以取 ...

  9. INVALID_SOCKET的值

    INVALID_SOCKET的值 (2011-06-26 15:06:45) 标签: 杂谈 INVALID_SOCKET的值不是-1,原因参考basetsd.h和WinSock2.h: typedef ...

  10. hdoj 5327 Olmpiad

    题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5327 #include<stdio.h> #include<cstring> ...