前端代碼相關規範

来源:https://www.cnblogs.com/imwtr/archive/2018/03/10/8539129.html
-Advertisement-
Play Games

總結一下目前在用的前端代碼規範,可作為開發參考 一、基礎規範 開發規範 項目目錄和文件的命名使用小寫字母,避免使用大寫或駝峰,多個單詞以下劃線 _ 分隔 如:my_project/cast_detail.js 目錄有複數意義的時候,使用複數命名 如 scripts images 某些第三方插件可直接 ...


總結一下目前在用的前端代碼規範,可作為開發參考

 

一、基礎規範

開發規範

項目目錄和文件的命名使用小寫字母,避免使用大寫或駝峰,多個單詞以下劃線 _ 分隔  如:my_project/cast_detail.js

目錄有複數意義的時候,使用複數命名  如 scripts  images

某些第三方插件可直接使用中劃線 - 作為文件名單詞的間隔 如 bootstrap-datepicker

某些特殊文件可以使用點號 . 作為文件名單詞的間隔 如  webpack.config.dev.js  jquery.cookie.min.js

使用有意義的英文單詞式命名,避免使用拼音式(如 tupian.png )命名

 

編輯器設置文件保存格式為 utf-8,以四個空格作為縮進(包括HTML,CSS,JS等),文件末尾空一行,行尾去掉空格

單個函數行數,以不超過一個屏幕為宜(50行左右),超出一個屏幕的,就要考慮拆分成更少的函數

每行代碼量不要太長,要適當進行分行(自己也可以在編輯器設置超長自動換行)

在 sublime 中的配置

{
    "default_encoding": "UTF-8",
    "ensure_newline_at_eof_on_save": true,
    "trim_trailing_white_space_on_save": true,
    "tab_size": 4,
    "translate_tabs_to_spaces": true,
    "word_wrap": "auto"
}

儘量做到代碼的整齊美觀

 

HTML規範

在頁面開頭使用DOCTYPE聲明啟用標準模式

不要忘了設置語言 language 和編碼 charset格式

各層元素應該換行,嵌套的元素節點應該縮進,縮進使用4個空格

屬性名統一使用小寫,使用中劃線 - 作為單詞的分隔;屬性值統一使用雙引號,避免使用單引號

不要在自動閉合標簽結尾處使用斜線(HTML5規範 指出他們是可選的,如 <img >)

不要忽略可選的閉合標簽(如 </li> )

<!DOCTYPE html>
<html lang="zh-CN">
    <head>
        <meta charset="UTF-8">
        <title>Page title</title>
        <!-- 選擇性地使用IE相容模式 -->
        <meta http-equiv="X-UA-Compatible" content="IE=Edge">
    </head>
    <body>
        <img src="images/company_logo.png" alt="Company">
 
        <h1 class="hello-world">Hello, world!</h1>
    </body>
</html>

引入CSS和JS時不需要指名type屬性

因為 text/css 和 text/javascript 已經是它們的預設值
另外,時刻牢記應該在 <head>中引入外部CSS,在<body>末尾引入外部JS

<!-- External CSS -->
<link rel="stylesheet" href="code_guide.css">
 
<!-- In-document CSS -->
<style>
    ...
</style>
 
<!-- External JS -->
<script src="code_guide.js"></script>
 
<!-- In-document JS -->
<script>
    ...
</script>

boolean值的屬性,不需要聲明值的屬性

在HTML5中,該屬性存在即為true,不存在即為false

<!-- 不建議 -->
<input type="text" disabled="disabled">
<!-- 建議 -->
<input type="text" disabled>
 
<!-- 不建議 -->
<input type="checkbox" value="1" checked="checked">
<input type="checkbox" value="1" checked>
 
<select>
    <option value="1" selected>1</option>
</select>

語義化,避免使用不需要的標簽,使用有意義的標簽

<!-- Not well -->
<p class="title">我是標題</p>
<span class="avatar">
    <img src="...">
</span>
 
<!-- Better -->
<h3>我是標題</h3>
<img class="avatar" src="...">

不要省略表格table 的 thead  tbody

<table>
    <thead>
        <tr>
            <th>ABC</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>abc</td>
        </tr>
    </tbody>
</table>

儘量使用HTML實體符而不是直接使用符號

使用<a>標簽作為JS事件處理時,統一使用 href="javascript:;" 偽協議。

因為設置了href之後的<a>標簽才具有預設 cursor: pointer 的樣式,才能支持Tab切換;

防止點擊跳轉可以使用 href="#",但頁面錨點hash會改變;可以使用 javascript:void(0) 但稍長;可以使用事件處理 return false;  event.preventDefault() 但略微麻煩

<!-- Not well -->
<a href="#">more>></a>
 
<!-- Better -->
<a href="javascript:;">more&gt;&gt;</a>

屬性應該按照特定的順序來保證易讀性

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

class是為高可復用組件設計的,所以應處在第一位;

id更加具體且應該儘量少使用,所以將它放在第二位。

<a class="..." id="..." data-modal="toggle" href="#">Example link</a>
 
<input class="form-control" type="text">
 
<img src="..." alt="...">

使用Smarty,Handlebars模板時,註意代碼的整潔美觀

儘量使用Map映射的結構,而不是條件判斷

<!-- Not well -->
<{if $title == 'one'}>
<h2>標題一</h2>
<{elseif $title == 'two'}>
<h2>標題二</h2>
<{elseif $title == 'three'}>
<h2>標題三</h2>
<{/if}>
 
<!-- Better -->
<{assign var="titleText" value=[
    'one' => '標題一',
    'two' => '標題二',
    'three' => '標題三'
]}>
<h2><{$titleText[$title]}></h2>

模板裡面符號兩端適當地加空格(逗號前不用)

<!-- 逗號後面有空格 -->
<li <{if in_array($beforeAction.currentUrl, $url)}>class="active"<{/if}> 列表 </li>
 
<!-- 等號兩邊有空格 -->
<{if $abc == 'cdf'}>
<{/if}>

自定義屬性統一使用 data- 首碼

一行標簽代碼不宜過長,超長時需要適當地按照屬性進行分行

但也不是說每個屬性都分行

<a class="r-btn r-btn-blue eva-content-btnSave" href="javascript:;"
   data-commentID="{{commentID}}"
   data-commentType="{{commentType}}"
   data-evaID="{{evaID}}"
   data-roleStaffID="{{roleStaffID}}"
>確認提交</a>

CSS規範

樣式文件頭部加上編碼規則 統一使用 UTF-8

@charset "UTF-8";

使用四個空格的縮進

每個屬性聲明末尾都要分號

關於空行

  • 文件最後保留一個空行
  • '}'後最好跟一個空行,包括scss中嵌套的規則
  • 屬性之間需要適當的空行
/* not good */
.element {
    ...
}
.dialog {
    color: red;
    &:after {
        ...
    }
}
 
/* good */
.element {
    ...
}
 
.dialog {
    color: red;
 
    &:after {
        ...
    }
}

關於換行

以下幾種情況不需要換行:

  • '{' 前

以下幾種情況需要換行:

  • '{' 後和 '}' 前
  • 每個屬性獨占一行
  • 多個規則的分隔符 ',' 後
/* not good */
.element
{color: red; background-color: black;}
 
/* good */
.element {
    color: red;
    background-color: black;
}
 
/* not good */
.element, .dialog {
    ...
}
 
/* good */
.element,
.dialog {
    ...
}

關於空格

以下幾種情況不需要空格:

  • 屬性名後
  • 多個規則的分隔符','前
  • !important '!' 後
  • 屬性值中 '(' 後和 ')' 前
  • 行末不要有多餘的空格

以下幾種情況需要空格:

  • 屬性值前
  • 選擇器 '>',  '+',  '~' 前後
  • '{' 前
  • !important '!' 前
  • @else 前後
  • 屬性值中的 ',' 後
  • 註釋 '/*' 後和 '*/' 前
/* not good */
.element {
    color :red! important;
    background-color: rgba(0,0,0,.5);
}
 
/* good */
.element {
    color: red !important;
    background-color: rgba(0, 0, 0, .5);
}
 
/* not good */
.element ,
.dialog{
    ...
}
 
/* good */
.element,
.dialog {
 
}
 
/* not good */
.element>.dialog{
    ...
}
 
/* good */
.element > .dialog{
    ...
}
 
/* not good */
.element{
    ...
}
 
/* good */
.element {
    ...
}
 
/* not good */
@if{
    ...
}@else{
    ...
}
 
/* good */
@if {
    ...
} @else {
    ...
}

屬性選擇器的屬性值需要引號,url 里的內容需要引號

.element:after {
    content: "";
    background-image: url("logo.png");
}
 
li[data-type="single"] {
    ...
}

類名參考 BEM命名規範

ID以及SASS中相關的變數命名使用小駝峰

/* class */
.form-content {
    ...
}
 
/* id */
#myDialog {
    ...
}
 
/* 變數 */
$colorBlack: #000;
 
/* 函數 */
@function pxToRem($px) {
    ...
}
 
/* 混合 */
@mixin centerBlock {
    ...
}
 
/* placeholder */
%myDialog {
    ...
}

顏色16進位用小寫字母,且儘量使用簡寫形式

/* not good */
.element {
    color: #ABCDEF;
    background-color: #001122;
}
 
/* good */
.element {
    color: #abcdef;
    background-color: #012;
}

不要為 0 指定單位,去掉小數點前後的 0

/* not good */
.element {
    color: rgba(0, 0, 0, 0.5);
}
 
/* good */
.element {
    color: rgba(0, 0, 0, .5);
}
 
/* not good */
.element {
    width: 50.0px;
}
 
/* good */
.element {
    width: 50px;
}
 
/* not good */
.element {
    width: 0px;
}
 
/* good */
.element {
    width: 0;
}

避免使用CSS中的@import ,應使用 <link>方式引入CSS文件

<!-- Not well -->
<style>
    @import url("more.css");
</style>
 
<!-- Better -->
<link rel="stylesheet" href="core.css">

@import 引入的文件不需要開頭的 '_' 和結尾的'.scss';

/* 引入 _variable.scss */
 
/* not good */
@import "_variable.scss";
 
/* good */
@import "variable";

儘量將媒體查詢的規則靠近與他們相關的規則

不要將他們一起整個放到一個獨立的樣式文件中,或者丟在文檔的最底部

使用首碼屬性時,應通過縮進使取值垂直對齊

且私有屬性在前,標準屬性在後

.selector {
    -webkit-box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
            box-shadow: 0 1px 2px rgba(0, 0, 0, .15);
}

註意屬性簡寫的使用,避免濫用導致覆蓋某些樣式

如果使用簡寫,需保證清楚相應順序的影響,且不會導致其他問題

  • padding
  • margin
  • background
  • border
  • border-radius
  • transition
  • animation
  • font

選擇器嵌套層數不宜過長

/* not good */
.table > thead > tr > th {}
.table > thead > tr > td {}
 
/* good */
.table > thead > tr {
    > th { … }
    > td {}
}

儘量不要在HTML中通過 style=... 內聯樣式

註意屬性的聲明順序

相關的屬性聲明應當歸為一組,參考按照下麵的順序排列,另參考

  1. Positioning  定位
  2. Box model  盒模型
  3. Typographic  排版
  4. Visual  外觀
  5. 其他
.declaration-order {
    /* Positioning */
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 100;
 
    /* Box-model */
    display: block;
    float: right;
    width: 100px;
    height: 100px;
 
    /* Typography */
    font: normal 13px "Helvetica Neue", sans-serif;
    line-height: 1.5;
    color: #333;
    text-align: center;
 
    /* Visual */
    background-color: #f5f5f5;
    border: 1px solid #e5e5e5;
    border-radius: 3px;
 
    /* Other */
    opacity: 1;
}

sublime中可安裝使用 CSSComb 插件進行格式轉換

  1 {
  2     // If plugin has trouble finding Node.js, replace this string with path
  3     // to your `node` bin
  4     "node-path" : ":/usr/local/bin",
  5     // Full list of supported options and acceptable values can be found here:
  6     // https://github.com/csscomb/csscomb.js/blob/master/doc/options.md
  7     "config": {
  8         // Whether to add a semicolon after the last value/mixin.
  9         "always-semicolon": true,
 10         // Set indent for code inside blocks, including media queries and nested rules.
 11         "block-indent": "    ",
 12         // Unify case of hexadecimal colors.
 13         "color-case": "lower",
 14         // Whether to expand hexadecimal colors or use shorthands.
 15         "color-shorthand": true,
 16         // Unify case of element selectors.
 17         "element-case": "lower",
 18         // Add/remove line break at EOF.
 19         "eof-newline": true,
 20         // Add/remove leading zero in dimensions.
 21         "leading-zero": false,
 22         // Unify quotes style.
 23         "quotes": "double",
 24         // Remove all rulesets that contain nothing but spaces.
 25         "remove-empty-rulesets": true,
 26         // Set space after `:` in declarations.
 27         "space-after-colon": " ",
 28         // Set space after combinator (for example, in selectors like `p > a`).
 29         "space-after-combinator": " ",
 30         // Set space after `{`.
 31         "space-after-opening-brace": "\n",
 32         // Set space after selector delimiter.
 33         "space-after-selector-delimiter": "\n",
 34         // Set space before `}`.
 35         "space-before-closing-brace": "\n",
 36         // Set space before `:` in declarations.
 37         "space-before-colon": "",
 38         // Set space before combinator (for example, in selectors like `p > a`).
 39         "space-before-combinator": " ",
 40         // Set space before `{`.
 41         "space-before-opening-brace": " ",
 42         // Set space before selector delimiter.
 43         "space-before-selector-delimiter": "",
 44         // Set space between declarations (i.e. `color: tomato`).
 45         "space-between-declarations": "\n",
 46         // Whether to trim trailing spaces.
 47         "strip-spaces": true,
 48         // Whether to remove units in zero-valued dimensions.
 49         "unitless-zero": true,
 50         // Whether to align prefixes in properties and values.
 51         "vendor-prefix-align": true,
 52         // Sort properties in particular order.
 53         "sort-order": [
 54                 "font",
 55                 "font-family",
 56                 "font-size",
 57                 "font-weight",
 58                 "font-style",
 59                 "font-variant",
 60                 "font-size-adjust",
 61                 "font-stretch",
 62                 "font-effect",
 63                 "font-emphasize",
 64                 "font-emphasize-position",
 65                 "font-emphasize-style",
 66                 "font-smooth",
 67                 "line-height",
 68                 "position",
 69                 "z-index",
 70                 "top",
 71                 "right",
 72                 "bottom",
 73                 "left",
 74                 "display",
 75                 "visibility",
 76                 "float",
 77                 "clear",
 78                 "overflow",
 79                 "overflow-x",
 80                 "overflow-y",
 81                 "-ms-overflow-x",
 82                 "-ms-overflow-y",
 83                 "clip",
 84                 "zoom",
 85                 "flex-direction",
 86                 "flex-order",
 87                 "flex-pack",
 88                 "flex-align",
 89                 "-webkit-box-sizing",
 90                 "-moz-box-sizing",
 91                 "box-sizing",
 92                 "width",
 93                 "min-width",
 94                 "max-width",
 95                 "height",
 96                 "min-height",
 97                 "max-height",
 98                 "margin",
 99                 "margin-top",
100                 "margin-right",
101                 "margin-bottom",
102                 "margin-left",
103                 "padding",
104                 "padding-top",
105                 "padding-right",
106                 "padding-bottom",
107                 "padding-left",
108                 "table-layout",
109                 "empty-cells",
110                 "caption-side",
111                 "border-spacing",
112                 "border-collapse",
113                 "list-style",
114                 "list-style-position",
115                 "list-style-type",
116                 "list-style-image",
117                 "content",
118                 "quotes",
119                 "counter-reset",
120                 "counter-increment",
121                 "resize",
122                 "cursor",
123                 "-webkit-user-select",
124                 "-moz-user-select",
125                 "-ms-user-select",
126                 "user-select",
127                 "nav-index",
128                 "nav-up",
129                 "nav-right",
130                 "nav-down",
131                 "nav-left",
132                 "-webkit-transition",
133                 "-moz-transition",
134                 "-ms-transition",
135                 "-o-transition",
136                 "transition",
137                 "-webkit-transition-delay",
138                 "-moz-transition-delay",
139                 "-ms-transition-delay",
140                 "-o-transition-delay",
141                 "transition-delay",
142                 "-webkit-transition-timing-function",
143                 "-moz-transition-timing-function",
144                 "-ms-transition-timing-function",
145                 "-o-transition-timing-function",
146                 "transition-timing-function",
147                 "-webkit-transition-duration",
148                 "-moz-transition-duration",
149                 "-ms-transition-duration",
150                 "-o-transition-duration",
151                 "transition-duration",
152                 "-webkit-transition-property",
153                 "-moz-transition-property",
154                 "-ms-transition-property",
155                 "-o-transition-property",
156                 "transition-property",
157                 "-webkit-transform",
158               

您的分享是我們最大的動力!

-Advertisement-
Play Games
更多相關文章
  • 準備階段 下載 Flutter SDK 新建 Flutter 文件夾,克隆 Flutter SDK: 配置 Flutter 環境 我是 Mac 系統,Flutter SDK 下載完後的路徑:Users/wuxiaolong/Flutter/flutter/ 。 在命令行下,進入用戶目錄 打開.bas ...
  • 以前不怎麼有這樣的需求,最近開發經常用到,所以就乾脆封裝一個這樣的 Button 讓圖片和字體都垂直居中,重寫layoutSubviews方法,來實現就可以,至於 layoutSubviews 方法什麼時候觸發,可以自行查下; ...
  • IBOutlet或IBAction符號對編譯不產生任何影響,它們只是標記,用於告訴Xcode這些對象可以和UI控制項進行關聯,以便於在編輯Interface Builder上的UI控制項的時候Xcode可以自動提示。 參考資料:《iOS編程指南》 ...
  • 近日,樓主在同一臺手機上,同時安裝同一個游戲的不同渠道包,add install後,提示:Failure [INSTALL_FAILED_DUPLICATE_PERMISSION perm=android.permission.具體許可權 pkg=渠道A游戲包名] 原因: 1、正要安裝的APP的自定義 ...
  • 當我們用RecyclerView時,如果想用某一個特定的版本,怎樣才能知道版本號呢?如果自己的筆記本中用過這個庫,那麼會保存在本地硬碟中。 Android自身依賴包的版本號本地存放路徑: 沒有用過該版本,也沒有關係,google develper中有說明:Support Library的版本號其實都 ...
  • 今天supprt28遇到的問題,由於28還是預覽版,還存在一些bug 都是因為如果程式內出現不同的,support或者其他外部引用庫的多個版本,Gradle在進行合併的時候會使用本地持有的,最高版本的來進行編譯,所以25的support就有可能引用26的東西,就會出現 屬性 merge 錯誤 ,或者 ...
  • 一、Gradle更新問題 Android Studio每次更新版本都會更新Gradle這個插件,而且有時候提示更新,卻一直更新不了,那是因為中國偉大的長城問題。就是下圖,我剛剛更新了,提示更新gradle,卻一直更新不了! 1.1 這有時候會導致停止在Refreshing Gradle Projec ...
  • 這個問題搞得我頭大,並且在查過百度後各位大佬給出的解釋我都不能理解,應該是我太白的原因,希望我寫的能好理解。 下麵文章視窗1、2、3,在代碼里分別為chuangkou、chuangkou1、chuangkou2. 下麵是我創建的一個及其簡易html框架結構: 製作這個網頁需要八個html文件,分別是 ...
一周排行
    -Advertisement-
    Play Games
  • 示例項目結構 在 Visual Studio 中創建一個 WinForms 應用程式後,項目結構如下所示: MyWinFormsApp/ │ ├───Properties/ │ └───Settings.settings │ ├───bin/ │ ├───Debug/ │ └───Release/ ...
  • [STAThread] 特性用於需要與 COM 組件交互的應用程式,尤其是依賴單線程模型(如 Windows Forms 應用程式)的組件。在 STA 模式下,線程擁有自己的消息迴圈,這對於處理用戶界面和某些 COM 組件是必要的。 [STAThread] static void Main(stri ...
  • 在WinForm中使用全局異常捕獲處理 在WinForm應用程式中,全局異常捕獲是確保程式穩定性的關鍵。通過在Program類的Main方法中設置全局異常處理,可以有效地捕獲並處理未預見的異常,從而避免程式崩潰。 註冊全局異常事件 [STAThread] static void Main() { / ...
  • 前言 給大家推薦一款開源的 Winform 控制項庫,可以幫助我們開發更加美觀、漂亮的 WinForm 界面。 項目介紹 SunnyUI.NET 是一個基於 .NET Framework 4.0+、.NET 6、.NET 7 和 .NET 8 的 WinForm 開源控制項庫,同時也提供了工具類庫、擴展 ...
  • 說明 該文章是屬於OverallAuth2.0系列文章,每周更新一篇該系列文章(從0到1完成系統開發)。 該系統文章,我會儘量說的非常詳細,做到不管新手、老手都能看懂。 說明:OverallAuth2.0 是一個簡單、易懂、功能強大的許可權+可視化流程管理系統。 有興趣的朋友,請關註我吧(*^▽^*) ...
  • 一、下載安裝 1.下載git 必須先下載並安裝git,再TortoiseGit下載安裝 git安裝參考教程:https://blog.csdn.net/mukes/article/details/115693833 2.TortoiseGit下載與安裝 TortoiseGit,Git客戶端,32/6 ...
  • 前言 在項目開發過程中,理解數據結構和演算法如同掌握蓋房子的秘訣。演算法不僅能幫助我們編寫高效、優質的代碼,還能解決項目中遇到的各種難題。 給大家推薦一個支持C#的開源免費、新手友好的數據結構與演算法入門教程:Hello演算法。 項目介紹 《Hello Algo》是一本開源免費、新手友好的數據結構與演算法入門 ...
  • 1.生成單個Proto.bat內容 @rem Copyright 2016, Google Inc. @rem All rights reserved. @rem @rem Redistribution and use in source and binary forms, with or with ...
  • 一:背景 1. 講故事 前段時間有位朋友找到我,說他的窗體程式在客戶這邊出現了卡死,讓我幫忙看下怎麼回事?dump也生成了,既然有dump了那就上 windbg 分析吧。 二:WinDbg 分析 1. 為什麼會卡死 窗體程式的卡死,入口門檻很低,後續往下分析就不一定了,不管怎麼說先用 !clrsta ...
  • 前言 人工智慧時代,人臉識別技術已成為安全驗證、身份識別和用戶交互的關鍵工具。 給大家推薦一款.NET 開源提供了強大的人臉識別 API,工具不僅易於集成,還具備高效處理能力。 本文將介紹一款如何利用這些API,為我們的項目添加智能識別的亮點。 項目介紹 GitHub 上擁有 1.2k 星標的 C# ...