l1n6yun's Blog

记录学习的技能和遇到的问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
/*****************************************
Copyright (c) 2004, Laser Lu
http://www.idow.net
*****************************************/
function convertCurrency(currencyDigits) {
// Constants:
var MAXIMUM_NUMBER = 99999999999.99;
// Predefine the radix characters and currency symbols for output:
var CN_ZERO = "零";
var CN_ONE = "壹";
var CN_TWO = "贰";
var CN_THREE = "叁";
var CN_FOUR = "肆";
var CN_FIVE = "伍";
var CN_SIX = "陆";
var CN_SEVEN = "柒";
var CN_EIGHT = "捌";
var CN_NINE = "玖";
var CN_TEN = "拾";
var CN_HUNDRED = "佰";
var CN_THOUSAND = "仟";
var CN_TEN_THOUSAND = "万";
var CN_HUNDRED_MILLION = "亿";
var CN_SYMBOL = "";
var CN_DOLLAR = "元";
var CN_TEN_CENT = "角";
var CN_CENT = "分";
var CN_INTEGER = "整";

// Variables:
var integral; // Represent integral part of digit number.
var decimal; // Represent decimal part of digit number.
var outputCharacters; // The output result.
var parts;
var digits, radices, bigRadices, decimals;
var zeroCount;
var i, p, d;
var quotient, modulus;

// Validate input string:
currencyDigits = currencyDigits.toString();
if (currencyDigits == "") {
PUT.alert("不能为空。");
return false;
}
if (currencyDigits.match(/[^,.\d]/) != null) {
PUT.alert("请输入数字。");
return '';
}
if ((currencyDigits).match(/^((\d{1,3}(,\d{3})*(.((\d{3},)*\d{1,3}))?)|(\d+(.\d+)?))$/) == null) {
PUT.alert("请输入正确数字。");
return false;
}

// Normalize the format of input digits:
currencyDigits = currencyDigits.replace(/,/g, ""); // Remove comma delimiters.
currencyDigits = currencyDigits.replace(/^0+/, ""); // Trim zeros at the beginning.
// Assert the number is not greater than the maximum number.
if (Number(currencyDigits) > MAXIMUM_NUMBER) {
PUT.alert("超出了最大数字转换。");
return false;
}

// Process the coversion from currency digits to characters:
// Separate integral and decimal parts before processing coversion:
parts = currencyDigits.split(".");
if (parts.length > 1) {
integral = parts[0];
decimal = parts[1];
// Cut down redundant decimal digits that are after the second.
decimal = decimal.substr(0, 2);
}
else {
integral = parts[0];
decimal = "";
}
// Prepare the characters corresponding to the digits:
digits = new Array(CN_ZERO, CN_ONE, CN_TWO, CN_THREE, CN_FOUR, CN_FIVE, CN_SIX, CN_SEVEN, CN_EIGHT, CN_NINE);
radices = new Array("", CN_TEN, CN_HUNDRED, CN_THOUSAND);
bigRadices = new Array("", CN_TEN_THOUSAND, CN_HUNDRED_MILLION);
decimals = new Array(CN_TEN_CENT, CN_CENT);
// Start processing:
outputCharacters = "";
// Process integral part if it is larger than 0:
if (Number(integral) > 0) {
zeroCount = 0;
for (i = 0; i < integral.length; i++) {
p = integral.length - i - 1;
d = integral.substr(i, 1);
quotient = p / 4;
modulus = p % 4;
if (d == "0") {
zeroCount++;
}
else {
if (zeroCount > 0)
{
outputCharacters += digits[0];
}
zeroCount = 0;
outputCharacters += digits[Number(d)] + radices[modulus];
}
if (modulus == 0 && zeroCount < 4) {
outputCharacters += bigRadices[quotient];
zeroCount = 0;
}
}
outputCharacters += CN_DOLLAR;
}
// Process decimal part if there is:
if (decimal != "") {
for (i = 0; i < decimal.length; i++) {
d = decimal.substr(i, 1);
if (d != "0") {
outputCharacters += digits[Number(d)] + decimals[i];
}
}
}
// Confirm and return the final output string:
if (outputCharacters == "") {
outputCharacters = CN_ZERO + CN_DOLLAR;
}
if (decimal == "") {
outputCharacters += CN_INTEGER;
}
outputCharacters = CN_SYMBOL + outputCharacters;
return outputCharacters;
}

使用方法:

1
2
3
4
5
6
convertCurrency(123.45)
"壹佰贰拾叁元肆角伍分"
convertCurrency(123000.45)
"壹拾贰万叁仟元肆角伍分"
convertCurrency(123456.78)
"壹拾贰万叁仟肆佰伍拾陆元柒角捌分"

create_code.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<?php
session_start();
//生成验证码图片
header("Content-type: image/png");
// 全数字
$str = "1,2,3,4,5,6,7,8,9,a,b,c,d,f,g"; //要显示的字符,可自己进行增删
$list = explode(",", $str);
$cmax = count($list) - 1;
$verifyCode = '';
for ( $i=0; $i < 5; $i++ ){
$randnum = mt_rand(0, $cmax);
$verifyCode .= $list[$randnum]; //取出字符,组合成为我们要的验证码字符
}
$_SESSION['code'] = $verifyCode; //将字符放入SESSION中

$im = imagecreate(58,28); //生成图片
$black = imagecolorallocate($im, 0,0,0); //此条及以下三条为设置的颜色
$white = imagecolorallocate($im, 255,255,255);
$gray = imagecolorallocate($im, 200,200,200);
$red = imagecolorallocate($im, 255, 0, 0);
imagefill($im,0,0,$white); //给图片填充颜色

//将验证码绘入图片
imagestring($im, 5, 10, 8, $verifyCode, $black); //将验证码写入到图片中

for($i=0;$i<50;$i++) //加入干扰象素
{
imagesetpixel($im, rand()p , rand()0 , $black); //加入点状干扰素
imagesetpixel($im, rand()p , rand()0 , $red);
imagesetpixel($im, rand()p , rand()0 , $gray);
//imagearc($im, rand()p, rand()p, 20, 20, 75, 170, $black); //加入弧线状干扰素
//imageline($im, rand()p, rand()p, rand()p, rand()p, $red); //加入线条状干扰素
}
imagepng($im);
imagedestroy($im);
?>

引用
demo.html

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title></title>
</head>

<body>
<form action="act.php" method="post">
<input type="text" name="code" />
<img id="code" src="create_code.php" alt="看不清楚,换一张" style="cursor: pointer; vertical-align:middle;" onClick="create_code()"/>

<button type="submit">提交</button>
</form>
<script>
function create_code(){
document.getElementById('code').src = 'create_code.php?'+Math.random()*10000;
}
</script>
</body>
</html>

//处理,判断是否输入正确
act.php

1
2
3
4
5
6
7
8
9
<?php
session_start();

if($_POST['code'] == $_SESSION['code']){
echo 'ok';
}else{
echo 'no';
}
?>

有没有觉得浏览器自带的原始滚动条很不美观,同时也有看到很多网站的自定义滚动条显得高端,就连 chrome32.0 开发板都抛弃了原始的滚动条,美观多了。那 ** webkit浏览器 ** 是如何自定义滚动条的呢?

前言

webkit 支持拥有 overflow 属性的区域,列表框,下拉菜单,textarea 的滚动条自定义样式,所以用处还是挺大的。当然,兼容所有浏览器的滚动条样式目前是不存在的。

演示

来看看这2个滚动条demo: demo1(图片版)、demo2(纯CSS3版)

滚动条组成

样式名 介绍
::-webkit-scrollbar 滚动条整体部分
::-webkit-scrollbar-thumb 滚动条里面的小方块,能向上向下移动(或往左往右移动,取决于是垂直滚动条还是水平滚动条)
::-webkit-scrollbar-track 滚动条的轨道(里面装有Thumb)
::-webkit-scrollbar-button 滚动条的轨道的两端按钮,允许通过点击微调小方块的位置。
::-webkit-scrollbar-track-piece 内层轨道,滚动条中间部分(除去)
::-webkit-scrollbar-corner 边角,即两个滚动条的交汇处
::-webkit-resizer 两个滚动条的交汇处上用于通过拖动调整元素大小的小控件

简洁版

这里就不贴出详细代码了, demo 里面可以通过查看源码寻找具体样式的设置。来看看 demo2 中第二个滚动条的样式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
/*定义滚动条高宽及背景 高宽分别对应横竖滚动条的尺寸*/  
::-webkit-scrollbar
{
width: 16px;
height: 16px;
background-color: #F5F5F5;
}

/*定义滚动条轨道 内阴影+圆角*/
::-webkit-scrollbar-track
{
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,0.3);
border-radius: 10px;
background-color: #F5F5F5;
}

/*定义滑块 内阴影+圆角*/
::-webkit-scrollbar-thumb
{
border-radius: 10px;
-webkit-box-shadow: inset 0 0 6px rgba(0,0,0,.3);
background-color: #555;
}

详细设置

定义滚动条就是利用伪元素与伪类,那什么是伪元素和伪类呢?

伪类大家应该很熟悉 :link , :focus , :hover ,此外 CSS3 中又增加了许多伪类选择器,如 :nth-child , :last-child , :nth-last-of-type() 等。

CSS 中的伪元素大家以前看过: :first-line , :first-letter , :before , :after 。那么在 CSS3 中,伪元素进行了调整,在以前的基础上增加了一个 : 也就是现在变成了” ::first-letter , ::first-line , ::before , ::after “,另外 CSS3 还增加了一个 ::selection 。两个 :: 和一个 : 在 CSS3 中主要用来区分伪类和伪元素。

webkit的伪类和伪元素的实现很强,可以把滚动条当成一个页面元素来定义,再结合一些高级的 CSS3 属性,比如渐变、圆角、RGBa等等。然后如果有些地方要用图片,可以把图片也可以转换成 Base64 ,不然每次都得加载那个多个图片,增加请求数。

任何对象都可以设置:边框、阴影、背景图片等等,创建的滚动条任然会按照操作系统本身的设置来完成其交互的行为。下面的伪类可以应用到上面的伪元素中。有点小复杂,具体怎么写可以看第一个 demo ,那里也有注释。

样式名 介绍
:horizontal horizontal 伪类适用于任何水平方向上的滚动条
:vertical vertical 伪类适用于任何垂直方向的滚动条
:decrement decrement 伪类适用于按钮和轨道碎片。表示递减的按钮或轨道碎片,例如可以使区域向上或者向右移动的区域和按钮
:increment increment 伪类适用于按钮和轨道碎片。表示递增的按钮或轨道碎片,例如可以使区域向下或者向左移动的区域和按钮
:start start 伪类适用于按钮和轨道碎片。表示对象(按钮 轨道碎片)是否放在滑块的前面
:end end 伪类适用于按钮和轨道碎片。表示对象(按钮 轨道碎片)是否放在滑块的后面
:double-button double-button 伪类适用于按钮和轨道碎片。判断轨道结束的位置是否是一对按钮。也就是轨道碎片紧挨着一对在一起的按钮。
:single-button single-button 伪类适用于按钮和轨道碎片。判断轨道结束的位置是否是一个按钮。也就是轨道碎片紧挨着一个单独的按钮。
:no-button no-button 伪类表示轨道结束的位置没有按钮。
:corner-present corner-present 伪类表示滚动条的角落是否存在。
:window-inactive 适用于所有滚动条,表示包含滚动条的区域,焦点不在该窗口的时候。
::-webkit-scrollbar-track-piece:start 滚动条上半边或左半边
::-webkit-scrollbar-thumb:window-inactive 当焦点不在当前区域滑块的状态
::-webkit-scrollbar-button:horizontal:decrement:hover 当鼠标在水平滚动条下面的按钮上的状态

导语:

Markdown 是一种轻量级的「标记语言」,它的优点很多,目前也被越来越多的写作爱好者,撰稿者广泛使用。看到这里请不要被「标记」、「语言」所迷惑,Markdown 的语法十分简单。常用的标记符号也不超过十个,这种相对于更为复杂的 HTML 标记语言来说,Markdown 可谓是十分轻量的,学习成本也不需要太多,且一旦熟悉这种语法规则,会有一劳永逸的效果。

Ulysses for Mac

Ulysses for Mac

一,认识 Markdown

在刚才的导语里提到,Markdown 是一种用来写作的轻量级「标记语言」,它用简洁的语法代替排版,而不像一般我们用的字处理软件 Word 或 Pages 有大量的排版、字体设置。它使我们专心于码字,用「标记」语法,来代替常见的排版格式。例如此文从内容到格式,甚至插图,键盘就可以通通搞定了。目前来看,支持 Markdown 语法的编辑器有很多,包括很多网站(例如简书)也支持了 Markdown 的文字录入。Markdown 从写作到完成,导出格式随心所欲,你可以导出 HTML 格式的文件用来网站发布,也可以十分方便的导出 PDF 格式,这种格式写出的简历更能得到 HR 的好感。甚至可以利用 CloudApp 这种云服务工具直接上传至网页用来分享你的文章,全球最大的轻博客平台 Tumblr,也支持 Mou 这类 Markdown 工具的直接上传。

Markdown 官方文档

这里可以看到官方的 Markdown 语法规则文档,当然,** 后文我也会用自己的方式阐述这些语法的具体用法 **。

  • 创始人 John Gruber 的 Markdown 语法说明
  • Markdown 中文版语法说明

使用 Markdown 的优点

  • 专注你的文字内容而不是排版样式,安心写作。
  • 轻松的导出 HTML、PDF 和本身的 .md 文件。
  • 纯文本内容,兼容所有的文本编辑器与字处理软件。
  • 随时修改你的文章版本,不必像字处理软件生成若干文件版本导致混乱。
  • 可读、直观、学习成本低。

使用 Markdown 的误区

*We believe that writing is about content, about what you want to say – not about fancy formatting. *
我们坚信写作写的是内容,所思所想,而不是花样格式。
— Ulysses for Mac

  • Markdown 旨在简洁、高效,也由于 Markdown 的易读易写,人们用不同的编程语言实现了多个版本的解析器和生成器,这就导致了目前不同的 Markdown 工具集成了不同的功能(基础功能大致相同),例如流程图与时序图,复杂表格与复杂公式的呈现,虽然功能的丰富并没有什么本质的缺点,但终归有些背离初衷,何况在编写的过程中很费神,不如使用专业的工具撰写来的更有效率,所以如果你需实现复杂功能,专业的图形界面工具会更加方便。** 当然,如果你对折腾这些不同客户端对 Markdown 的定制所带来高阶功能感到愉悦的话,那也是无可厚非的。 **

flowchart.js on Github(使用 Markdown 绘制流程图)

flowchart.js on Github(使用 Markdown 绘制流程图)

我该用什么工具?

Mou for Mac

Mou for Mac

  • 在 Mac OS X 上,我强烈建议你用 Mou 这款免费且十分好用的 Markdown 编辑器,它支持实时预览,既左边是你编辑 Markdown 语言,右边会实时的生成预览效果。不仅如此,Mou 还有一些有趣的偏好设置(Preference),例如主题(Themes)与样式(CSS),它们可以配置出定制化的文本编辑效果与导出效果,如果你对自带的主题与样式不满意还可以到 GitHub 上搜索其它爱好者为 Mou 编写的更多主题样式,导入的方式可以在偏好设置的 Themes 或 CSS 选项中 选择 reload。

Mou 的编写与预览窗口

Mou 的编写与预览窗口

如果你从事文字工作,我强烈建议你购买 Ulysses for Mac,这款软件入围了苹果 Mac App Store 的 The Best of 2013。它支持更多的写作格式、多文档的支持。Mou,iA writer 这些软件都是基于单文档的管理方式,而 Ulysses 支持 Folder、Filter 的管理,一个 Folder 里面可以创建多个 Sheet,Sheet 之间也可以进行 Combine 处理。

Mac 上一些 Markdown 编辑器

Mac 上一些 Markdown 编辑器

  • 由于笔者很少接触 Windows,Windows 下的 Markdown 没有过多涉猎,经朋友介绍,有两款还算不错,一款叫做 MarkdownPad ,另一款叫做 MarkPad。
  • iOS 端很多 app 早已经支持了 Markdown 录入,例如 Drafts,Day One,iA writer 等,另外 Ulysses for iPad 现在已经上架,可以说是 iOS 平台最好的编辑器了。
  • 在 Web端,我强烈推荐简书这款产品,上面有无数热爱文字的人在不停的创造,分享。在 Web 端使用 Markdown * 没有比简书更舒服的地方了,同样支持左右两栏的实时预览,字体优雅,简洁。

简书的编辑预览模式

简书的编辑预览模式

二,Markdown 语法的简要规则

标题

标题

标题

标题是每篇文章都需要也是最常用的格式,在 Markdown 中,如果一段文字被定义为标题,只要在这段文字前加 # 号即可。

# 一级标题

## 二级标题

### 三级标题

以此类推,总共六级标题,建议在井号后加一个空格,这是最标准的 Markdown 语法。

列表

熟悉 HTML 的同学肯定知道有序列表与无序列表的区别,在 Markdown 下,列表的显示只需要在文字前加上 - 或 * 即可变为无序列表,有序列表则直接在文字前加1. 2. 3. 符号要和文字之间加上一个字符的空格。

无序列表与有序列表

无序列表与有序列表

引用

如果你需要引用一小段别处的句子,那么就要用引用的格式。

例如这样

只需要在文本前加入 > 这种尖括号(大于号)即可

引用

引用

图片与链接

插入链接与插入图片的语法很像,区别在一个 ! 号

图片为:![](){ImgCap}{/ImgCap}

链接为:[]()

插入图片的地址需要图床,这里推荐围脖图床修复计划 与 CloudApp 的服务,生成URL地址即可。

URL 与图片

URL 与图片

粗体与斜体

Markdown 的粗体和斜体也非常简单,用两个 * 包含一段文本就是粗体的语法,用一个 * 包含一段文本就是斜体的语法。

例如:** 这里是粗体 ** * 这里是斜体 *

表格

表格是我觉得 Markdown 比较累人的地方,例子如下:

1
2
3
4
5
| Tables        | Are           | Cool  |
| ------------- |:-------------:| -----:|
| col 3 is | right-aligned | $1600 |
| col 2 is | centered | $12 |
| zebra stripes | are neat | $1 |

这种语法生成的表格如下:

Tables Are Cool
col 3 is right-aligned $1600
col 2 is centered $12
zebra stripes are neat $1

代码框

如果你是个程序猿,需要在文章里优雅的引用代码框,在 Markdown下实现也非常简单,只需要用两个 ` 把中间的代码包裹起来。图例:

使用 `tab` 键即可缩进

使用 tab 键即可缩进。

分割线

分割线的语法只需要三个 * 号,例如:


[ 到这里,Markdown 的基本语法在日常的使用中基本就没什么大问题了,只要多加练习,配合好用的工具,写起东西来肯定会行云流水。更多的语法规则,其实 Mou 的 Help 文档栗子很好,当你第一次使用 Mou 时,就会显示该文档。可以用来对用的查找和学习。

三,相关推荐:

工具

图床工具用来上传图片获取 URL 地址

  • Droplr
  • Cloudapp
  • ezShare for Mac
  • 围脖图床修复计划

在线好用的Markdown工具,为印象笔记而生

  • 马克飞象,专为印象笔记打造的Markdown编辑器,非常推荐

相关文章阅读:

  • 为什么作家应该用 Markdown 保存自己的文稿
  • Markdown写作浅谈
  • Markdown 工具补完
  • Drafts + Scriptogr.am + Dropbox 打造移动端 Markdown 风格博客
  • 图灵社区,怎样使用Markdown
  • 为什么我们要学习Markdown的三个理由
  • Markdown 语法写作入门指南 by ibuick

对于文件夹:

1、解除对某磁盘某个文件夹的强行隐藏(示例):

1
attrib d:\"Program Files" -s -h /s /d

2、解除对某磁盘全部文件夹的强行隐藏(示例):

1
attrib d:\"*" -s -h /s /d

——友情提示:以上示例中,d:为磁盘盘符;引号内为文件夹名称;相关命令参数:

参数 注释
+r 设置只读文件属性。
-r 清除只读文件属性。
+a 设置存档属性。
-a 清除存档属性。
+s 设置系统文件属性。
-s 清除系统文件属性。
+h 设置隐藏文件属性。
-h 清除隐藏文件属性。
/s 将attrib和任意命令行选项应用到当前目录及其所有子目录中的匹配文件。
/d 将attrib和任意命令行选项应用到目录。
/? 在命令提示符下显示帮助。

对于文件:

1
ATTRIB [+R | -R] [+A | -A ] [+S | -S] [+H | -H] [[drive:] [path] filename] [/S [ /D]]
参数 注释
+ 设置属性。
- 清除属性。
R 只读文件属性。
A 存档文件属性。
S 系统文件属性。
H 隐藏文件属性。
[drive:][path][filename] 指定要处理的文件属性。
/S 处理当前文件夹及其子文件夹中的匹配文件。
/D 也处理文件夹。

例如:

1
attrib -s -h -r c:\*.*

执行reg

1
2
3
4
Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Authentication\LogonUI\Background]
"OEMBackground"=dword:00000001

添加图片

打开文件夹C:\Windows\System32\oobe\info\backgrounds(如果没有这个文件夹的请自行创建)。

添加自己选择好的图片,文件名修改成backgroundDefault.jpg.

注:我们编辑好的登录界面的背景图片backgroundDefault.jpg,其体积一定控制在250KB以内;否则,我们修改后的登录界面的背景图片就无法了.

此文档包含了用Chart.js创建漂亮图表的所有知识。

起步

引入Chart.js文件

首先我们需要在页面中引入Chart.js文件。此工具库在全局命名空间中定义了Chart变量。

1
<script src="Chart.js"></script>

创建图表

为了创建图表,我们要实例化一个Chart对象。为了完成前面的步骤,首先需要需要传入一个绘制图表的2d context。以下是案例。

1
<canvas id="myChart" width="400" height="400"></canvas>
1
2
3
//Get the context of the canvas element we want to select
var ctx = document.getElementById("myChart").getContext("2d");
var myNewChart = new Chart(ctx).PolarArea(data);

我们还可以用jQuery获取canvas的context。首先从jQuery集合中获取我们需要的DOM节点,然后在这个DOM节点上调用 getContext(“2d”) 方法。

1
2
3
4
//Get context with jQuery - using jQuery's .get() method.
var ctx = $("#myChart").get(0).getContext("2d");
//This will get the first returned node in the jQuery collection.
var myNewChart = new Chart(ctx);

当我们完成了在指定的canvas上实例化Chart对象之后,Chart.js会自动针对retina屏幕做缩放。

Chart对象设置完成后,我们就可以继续创建Chart.js中提供的具体类型的图表了。下面这个案例中,我们将展示如何绘制一幅极地区域图(Polar area chart)。

1
new Chart(ctx).PolarArea(data,options);

We call a method of the name of the chart we want to create. We pass in the data for that chart type, and the options for that chart as parameters. Chart.js will merge the options you pass in with the default options for that chart type.

曲线图(Line chart)

简介

曲线图就是将数据标于曲线上的一种图表。

一般用于展示趋势数据,和比较两组数据集。

使用案例

1
new Chart(ctx).Line(data,options);

数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}

The line chart requires an array of labels for each of the data points. This is show on the X axis.

The data for line charts is broken up into an array of datasets. Each dataset has a colour for the fill, a colour for the line and colours for the points and strokes of the points. These colours are strings just like CSS. You can use RGBA, RGB, HEX or HSL notation.

图表参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
Line.defaults = {

//Boolean - If we show the scale above the chart data
scaleOverlay : false,

//Boolean - If we want to override with a hard coded scale
scaleOverride : false,

//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The scale starting value
scaleStartValue : null,

//String - Colour of the scale line
scaleLineColor : "rgba(0,0,0,.1)",

//Number - Pixel width of the scale line
scaleLineWidth : 1,

//Boolean - Whether to show labels on the scale
scaleShowLabels : false,

//Interpolated JS string - can access value
scaleLabel : "<%=value%>",

//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",

//Number - Scale label font size in pixels
scaleFontSize : 12,

//String - Scale label font weight style
scaleFontStyle : "normal",

//String - Scale label font colour
scaleFontColor : "#666",

///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,

//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",

//Number - Width of the grid lines
scaleGridLineWidth : 1,

//Boolean - Whether the line is curved between points
bezierCurve : true,

//Boolean - Whether to show a dot for each point
pointDot : true,

//Number - Radius of each point dot in pixels
pointDotRadius : 3,

//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,

//Boolean - Whether to show a stroke for datasets
datasetStroke : true,

//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,

//Boolean - Whether to fill the dataset with a colour
datasetFill : true,

//Boolean - Whether to animate the chart
animation : true,

//Number - Number of animation steps
animationSteps : 60,

//String - Animation easing effect
animationEasing : "easeOutQuart",

//Function - Fires when the animation is complete
onAnimationComplete : null

}

柱状图(Bar chart)

简介

A bar chart is a way of showing data as bars.

It is sometimes used to show trend data, and the comparison of multiple data sets side by side.

使用案例

1
new Chart(ctx).Bar(data,options);

数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
var data = {
labels : ["January","February","March","April","May","June","July"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
data : [28,48,40,19,96,27,100]
}
]
}

The bar chart has the a very similar data structure to the line chart, and has an array of datasets, each with colours and an array of data. Again, colours are in CSS format.

We have an array of labels too for display. In the example, we are showing the same data as the previous line chart example.

图表参数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
Bar.defaults = {

//Boolean - If we show the scale above the chart data
scaleOverlay : false,

//Boolean - If we want to override with a hard coded scale
scaleOverride : false,

//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The scale starting value
scaleStartValue : null,

//String - Colour of the scale line
scaleLineColor : "rgba(0,0,0,.1)",

//Number - Pixel width of the scale line
scaleLineWidth : 1,

//Boolean - Whether to show labels on the scale
scaleShowLabels : false,

//Interpolated JS string - can access value
scaleLabel : "<%=value%>",

//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",

//Number - Scale label font size in pixels
scaleFontSize : 12,

//String - Scale label font weight style
scaleFontStyle : "normal",

//String - Scale label font colour
scaleFontColor : "#666",

///Boolean - Whether grid lines are shown across the chart
scaleShowGridLines : true,

//String - Colour of the grid lines
scaleGridLineColor : "rgba(0,0,0,.05)",

//Number - Width of the grid lines
scaleGridLineWidth : 1,

//Boolean - If there is a stroke on each bar
barShowStroke : true,

//Number - Pixel width of the bar stroke
barStrokeWidth : 2,

//Number - Spacing between each of the X value sets
barValueSpacing : 5,

//Number - Spacing between data sets within X values
barDatasetSpacing : 1,

//Boolean - Whether to animate the chart
animation : true,

//Number - Number of animation steps
animationSteps : 60,

//String - Animation easing effect
animationEasing : "easeOutQuart",

//Function - Fires when the animation is complete
onAnimationComplete : null

}

雷达图或蛛网图(Radar chart)

简介

A radar chart is a way of showing multiple data points and the variation between them.

They are often useful for comparing the points of two or more different data sets

使用案例

1
new Chart(ctx).Radar(data,options);

数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
var data = {
labels : ["Eating","Drinking","Sleeping","Designing","Coding","Partying","Running"],
datasets : [
{
fillColor : "rgba(220,220,220,0.5)",
strokeColor : "rgba(220,220,220,1)",
pointColor : "rgba(220,220,220,1)",
pointStrokeColor : "#fff",
data : [65,59,90,81,56,55,40]
},
{
fillColor : "rgba(151,187,205,0.5)",
strokeColor : "rgba(151,187,205,1)",
pointColor : "rgba(151,187,205,1)",
pointStrokeColor : "#fff",
data : [28,48,40,19,96,27,100]
}
]
}

For a radar chart, usually you will want to show a label on each point of the chart, so we include an array of strings that we show around each point in the chart. If you do not want this, you can either not include the array of labels, or choose to hide them in the chart options.

For the radar chart data, we have an array of datasets. Each of these is an object, with a fill colour, a stroke colour, a colour for the fill of each point, and a colour for the stroke of each point. We also have an array of data values.

图表

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
Radar.defaults = {

//Boolean - If we show the scale above the chart data
scaleOverlay : false,

//Boolean - If we want to override with a hard coded scale
scaleOverride : false,

//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The centre starting value
scaleStartValue : null,

//Boolean - Whether to show lines for each scale point
scaleShowLine : true,

//String - Colour of the scale line
scaleLineColor : "rgba(0,0,0,.1)",

//Number - Pixel width of the scale line
scaleLineWidth : 1,

//Boolean - Whether to show labels on the scale
scaleShowLabels : false,

//Interpolated JS string - can access value
scaleLabel : "<%=value%>",

//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",

//Number - Scale label font size in pixels
scaleFontSize : 12,

//String - Scale label font weight style
scaleFontStyle : "normal",

//String - Scale label font colour
scaleFontColor : "#666",

//Boolean - Show a backdrop to the scale label
scaleShowLabelBackdrop : true,

//String - The colour of the label backdrop
scaleBackdropColor : "rgba(255,255,255,0.75)",

//Number - The backdrop padding above & below the label in pixels
scaleBackdropPaddingY : 2,

//Number - The backdrop padding to the side of the label in pixels
scaleBackdropPaddingX : 2,

//Boolean - Whether we show the angle lines out of the radar
angleShowLineOut : true,

//String - Colour of the angle line
angleLineColor : "rgba(0,0,0,.1)",

//Number - Pixel width of the angle line
angleLineWidth : 1,

//String - Point label font declaration
pointLabelFontFamily : "'Arial'",

//String - Point label font weight
pointLabelFontStyle : "normal",

//Number - Point label font size in pixels
pointLabelFontSize : 12,

//String - Point label font colour
pointLabelFontColor : "#666",

//Boolean - Whether to show a dot for each point
pointDot : true,

//Number - Radius of each point dot in pixels
pointDotRadius : 3,

//Number - Pixel width of point dot stroke
pointDotStrokeWidth : 1,

//Boolean - Whether to show a stroke for datasets
datasetStroke : true,

//Number - Pixel width of dataset stroke
datasetStrokeWidth : 2,

//Boolean - Whether to fill the dataset with a colour
datasetFill : true,

//Boolean - Whether to animate the chart
animation : true,

//Number - Number of animation steps
animationSteps : 60,

//String - Animation easing effect
animationEasing : "easeOutQuart",

//Function - Fires when the animation is complete
onAnimationComplete : null

}

极地区域图(Polar area chart)

简介

Polar area charts are similar to pie charts, but each segment has the same angle - the radius of the segment differs depending on the value.

This type of chart is often useful when we want to show a comparison data similar to a pie chart, but also show a scale of values for context.

使用案例

1
new Chart(ctx).PolarArea(data,options);

数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
var data = [
{
value : 30,
color: "#D97041"
},
{
value : 90,
color: "#C7604C"
},
{
value : 24,
color: "#21323D"
},
{
value : 58,
color: "#9D9B7F"
},
{
value : 82,
color: "#7D4F6D"
},
{
value : 8,
color: "#584A5E"
}
]

As you can see, for the chart data you pass in an array of objects, with a value and a colour. The value attribute should be a number, while the color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.

图表

These are the default chart options. By passing in an object with any of these attributes, Chart.js will merge these objects and the graph accordingly. Explanations of each option are commented in the code below.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
PolarArea.defaults = {

//Boolean - Whether we show the scale above or below the chart segments
scaleOverlay : true,

//Boolean - If we want to override with a hard coded scale
scaleOverride : false,

//** Required if scaleOverride is true **
//Number - The number of steps in a hard coded scale
scaleSteps : null,
//Number - The value jump in the hard coded scale
scaleStepWidth : null,
//Number - The centre starting value
scaleStartValue : null,

//Boolean - Show line for each value in the scale
scaleShowLine : true,

//String - The colour of the scale line
scaleLineColor : "rgba(0,0,0,.1)",

//Number - The width of the line - in pixels
scaleLineWidth : 1,

//Boolean - whether we should show text labels
scaleShowLabels : true,

//Interpolated JS string - can access value
scaleLabel : "<%=value%>",

//String - Scale label font declaration for the scale label
scaleFontFamily : "'Arial'",

//Number - Scale label font size in pixels
scaleFontSize : 12,

//String - Scale label font weight style
scaleFontStyle : "normal",

//String - Scale label font colour
scaleFontColor : "#666",

//Boolean - Show a backdrop to the scale label
scaleShowLabelBackdrop : true,

//String - The colour of the label backdrop
scaleBackdropColor : "rgba(255,255,255,0.75)",

//Number - The backdrop padding above & below the label in pixels
scaleBackdropPaddingY : 2,

//Number - The backdrop padding to the side of the label in pixels
scaleBackdropPaddingX : 2,

//Boolean - Stroke a line around each segment in the chart
segmentShowStroke : true,

//String - The colour of the stroke on each segement.
segmentStrokeColor : "#fff",

//Number - The width of the stroke value in pixels
segmentStrokeWidth : 2,

//Boolean - Whether to animate the chart or not
animation : true,

//Number - Amount of animation steps
animationSteps : 100,

//String - Animation easing effect.
animationEasing : "easeOutBounce",

//Boolean - Whether to animate the rotation of the chart
animateRotate : true,

//Boolean - Whether to animate scaling the chart from the centre
animateScale : false,

//Function - This will fire when the animation of the chart is complete.
onAnimationComplete : null
}

饼图(Pie chart)

简介

Pie charts are probably the most commonly used chart there are. They are divided into segments, the arc of each segment shows a the proportional value of each piece of data.

They are excellent at showing the relational proportions between data.

使用案例

1
new Chart(ctx).Pie(data,options);

数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
var data = [
{
value: 30,
color:"#F38630"
},
{
value : 50,
color : "#E0E4CC"
},
{
value : 100,
color : "#69D2E7"
}
]

For a pie chart, you must pass in an array of objects with a value and a color property. The value attribute should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. The color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.

图表

These are the default options for the Pie chart. Pass in an object with any of these attributes to override them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
Pie.defaults = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke : true,

//String - The colour of each segment stroke
segmentStrokeColor : "#fff",

//Number - The width of each segment stroke
segmentStrokeWidth : 2,

//Boolean - Whether we should animate the chart
animation : true,

//Number - Amount of animation steps
animationSteps : 100,

//String - Animation easing effect
animationEasing : "easeOutBounce",

//Boolean - Whether we animate the rotation of the Pie
animateRotate : true,

//Boolean - Whether we animate scaling the Pie from the centre
animateScale : false,

//Function - Will fire on animation completion.
onAnimationComplete : null
}

环形图(Doughnut chart)

简介

Doughnut charts are similar to pie charts, however they have the centre cut out, and are therefore shaped more like a doughnut than a pie!

They are aso excellent at showing the relational proportions between data.

使用案例

1
new Chart(ctx).Doughnut(data,options);

数据结构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
var data = [
{
value: 30,
color:"#F7464A"
},
{
value : 50,
color : "#E2EAE9"
},
{
value : 100,
color : "#D4CCC5"
},
{
value : 40,
color : "#949FB1"
},
{
value : 120,
color : "#4D5360"
}

]

For a doughnut chart, you must pass in an array of objects with a value and a color property. The value attribute should be a number, Chart.js will total all of the numbers and calculate the relative proportion of each. The color attribute should be a string. Similar to CSS, for this string you can use HEX notation, RGB, RGBA or HSL.

图表

These are the default options for the doughnut chart. Pass in an object with any of these attributes to override them.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
Doughnut.defaults = {
//Boolean - Whether we should show a stroke on each segment
segmentShowStroke : true,

//String - The colour of each segment stroke
segmentStrokeColor : "#fff",

//Number - The width of each segment stroke
segmentStrokeWidth : 2,

//The percentage of the chart that we cut out of the middle.
percentageInnerCutout : 50,

//Boolean - Whether we should animate the chart
animation : true,

//Number - Amount of animation steps
animationSteps : 100,

//String - Animation easing effect
animationEasing : "easeOutBounce",

//Boolean - Whether we animate the rotation of the Doughnut
animateRotate : true,

//Boolean - Whether we animate scaling the Doughnut from the centre
animateScale : false,

//Function - Will fire on animation completion.
onAnimationComplete : null
}

General issues

Chart interactivity

If you are looking to add interaction as a layer to charts, Chart.js is not the library for you. A better option would be using SVG, as this will let you attach event listeners to any of the elements in the chart, as these are all DOM nodes.

Chart.js uses the canvas element, which is a single DOM node, similar in characteristics to a static image. This does mean that it has a wider scope for compatibility, and less memory implications than SVG based charting solutions. The canvas element also allows for saving the contents as a base 64 string, allowing saving the chart as an image.

In SVG, all of the lines, data points and everything you see is a DOM node. As a result of this, complex charts with a lot of intricacies, or many charts on the page will often see dips in performance when scrolling or generating the chart, especially when there are multiple on the page. SVG also has relatively poor mobile support, with Android not supporting SVG at all before version 3.0, and iOS before 5.0. (caniuse.com/svg-html5).

浏览器支持

所有现代浏览器和大部分手机浏览器都支持canvas(caniuse.com/canvas)。

对于IE8及以下版本的浏览器,建议使用ExplorerCanvas - 见 https://code.google.com/p/explorercanvas/。对于不支持canvas的IE会自动降级为VML格式。使用方法:

1
2
3
<head>

</head>

Usually I would recommend feature detection to choose whether or not to load a polyfill, rather than IE conditional comments, however in this case, VML is a Microsoft proprietary format, so it will only work in IE.

Some important points to note in my experience using ExplorerCanvas as a fallback.

  • Initialise charts on load rather than DOMContentReady when using the library, as sometimes a race condition will occur, and it will result in an error when trying to get the 2d context of a canvas.

  • New VML DOM elements are being created for each animation frame and there is no hardware acceleration. As a result animation is usually slow and jerky, with flashing text. It is a good idea to dynamically turn off animation based on canvas support. I recommend using the excellent Modernizr to do this.

  • When declaring fonts, the library explorercanvas requires the font name to be in single quotes inside the string. For example, instead of your scaleFontFamily property being simply “Arial”, explorercanvas support, use “‘Arial’” instead. Chart.js does this for default values.

Bugs & issues

Please report these on the Github page - at github.com/nnnick/Chart.js.

New contributions to the library are welcome.

License

Chart.js is open source and available under the MIT license.

前两天调试 Web 应用的时候,需要改一下 cookie 值来测试不同用户状态。打开开发者工具找 Application 面板、再展开 Cookies 找到对应的域名,操作起来有点繁琐。

想了想,能不能搞个简单的书签脚本,一键查看和修改 cookie?

代码实现

1
document.cookie = window.prompt("COOKIE编辑器", document.cookie);void(0);

就这么几行,简洁得不行。

原理说明

  1. document.cookie 读取当前页面的所有 cookie
  2. window.prompt() 弹出一个输入框,第一个参数是提示文字,第二个参数是输入框的默认值
  3. 用户编辑后点击确定,返回值赋给 document.cookie,完成修改
  4. void(0) 防止书签跳转页面

使用方法

把下面这段存成书签的 URL:

1
javascript:document.cookie=window.prompt("COOKIE编辑器",document.cookie);void(0);

在任意页面点击这个书签,就能看到当前站点的 cookie,改完点确定就生效了。

最近逛 QQ 空间的时候,看到好友动态多了起来,一个个点赞太累了。想着能不能搞个脚本自动点赞,省得手动操作。

研究了一下 QQ 空间页面的 DOM 结构,发现点赞按钮有个特征属性 data-clicklog='like',利用这个就能定位到所有点赞按钮。

脚本代码

1
2
3
4
5
6
7
8
9
10
jQuery("a.qz_like_btn_v3[data-clicklog='like']").each(function(index, item) {
jQuery(item).trigger('click');
});

jQuery(window).scroll(function() {
jQuery("a.qz_like_btn_v3[data-clicklog='like']").each(function(index, item) {
jQuery(item).trigger('click');
});
return true;
});

怎么用

这段代码可以保存成书签(Bookmarklet),使用方法很简单:

  1. 创建一个新的书签,名称随便起,比如「QQ空间一键点赞」
  2. 把 URL 填成 javascript: 加上上面的代码(压缩成一行)
  3. 打开 QQ 空间好友动态页面
  4. 点击这个书签,当前页面的动态就会自动点赞
  5. 向下滑动加载更多动态,脚本会自动给新出现的动态点赞

完整书签代码

把下面这段复制到书签 URL 里就行:

1
javascript:jQuery("a.qz_like_btn_v3[data-clicklog='like']").each(function(index, item) {jQuery(item).trigger('click');});jQuery(window).scroll(function() {jQuery("a.qz_like_btn_v3[data-clicklog='like']").each(function(index, item) {jQuery(item).trigger('click');});return true;});

这个小程序虽然简单,但还挺实用的,分享给有需要的朋友。

目录

  • HTML
    • 语法
    • HTML5 doctype
    • 语言属性(Language attribute)
    • 字符编码
    • IE 兼容模式
    • 引入 CSS 和 JavaScript 文件
    • 实用为王
    • 属性顺序
    • 布尔(boolean)型属性
    • 减少标签的数量
    • JavaScript 生成的标签
  • CSS
    • 语法
    • 声明顺序
    • 媒体查询(Media query)的位置
    • 带前缀的属性
    • 单行规则声明
    • 简写形式的属性声明
    • Less 和 Sass 中的嵌套
    • 注释
    • class 命名
    • 选择器
    • 代码组织

黄金定律

永远遵循同一套编码规范 – 可以是这里列出的,也可以是你自己总结的。如果你发现本规范中有任何错误,敬请指正。通过 open an issue on GitHub为本规范添加或贡献内容。

不管有多少人共同参与同一项目,一定要确保每一行代码都像是同一个人编写的。

HTML

语法

  • 用两个空格来代替制表符(tab) – 这是唯一能保证在所有环境下获得一致展现的方法。
  • 嵌套元素应当缩进一次(即两个空格)。
  • 对于属性的定义,确保全部使用双引号,绝不要使用单引号。
  • 不要在自闭合(self-closing)元素的尾部添加斜线 – HTML5 规范中明确说明这是可选的。
  • 不要省略可选的结束标签(closing tag)(例如,</li> 或 </body>)。
1
2
3
4
5
6
7
8
9
10
<!DOCTYPE html>
<html>
<head>
<title>Page title</title>
</head>
<body>
<img src="images/company-logo.png" alt="Company">
<h1 class="hello-world">Hello, world!</h1>
</body>
</html>

HTML5 doctype

为每个 HTML 页面的第一行添加标准模式(standard mode)的声明,这样能够确保在每个浏览器中拥有一致的展现。

1
2
3
4
5
<!DOCTYPE html>
<html>
<head>
</head>
</html>

语言属性

根据 HTML5 规范:

强烈建议为 html 根元素指定 lang 属性,从而为文档设置正确的语言。这将有助于语音合成工具确定其所应该采用的发音,有助于翻译工具确定其翻译时所应遵守的规则等等。
更多关于 lang 属性的知识可以从 此规范 中了解。

这里列出了语言代码表。

1
2
3
<html lang="zh-CN">

</html>

IE 兼容模式

IE 支持通过特定的 <meta> 标签来确定绘制当前页面所应该采用的 IE 版本。除非有强烈的特殊需求,否则最好是设置为 edge mode,从而通知 IE 采用其所支持的最新的模式。

阅读这篇 stack overflow 上的文章可以获得更多有用的信息。

1
<meta http-equiv="X-UA-Compatible" content="IE=Edge">

字符编码

通过明确声明字符编码,能够确保浏览器快速并容易的判断页面内容的渲染方式。这样做的好处是,可以避免在 HTML 中使用字符实体标记(character entity),从而全部与文档编码一致(一般采用 UTF-8 编码)。

1
2
3
<head>
<meta charset="UTF-8">
</head>

引入 CSS 和 JavaScript 文件

根据 HTML5 规范,在引入 CSS 和 JavaScript 文件时一般不需要指定 type 属性,因为 text/css 和 text/javascript 分别是它们的默认值。

  • Using link
  • Using style
  • Using script
1
2
3
4
5
6
7
8
9
10

<link rel="stylesheet" href="code-guide.css">


<style>
/* ... */
</style>


<script src="code-guide.js"></script>

实用为王

尽量遵循 HTML 标准和语义,但是不要以牺牲实用性为代价。任何时候都要尽量使用最少的标签并保持最小的复杂度。

属性顺序

HTML 属性应当按照以下给出的顺序依次排列,确保代码的易读性。

  • class
  • id, name
  • data-*
  • src, for, type, href
  • title, alt
  • aria-*, role

class 用于标识高度可复用组件,因此应该排在首位。id 用于标识具体组件,应当谨慎使用(例如,页面内的书签),因此排在第二位。

1
2
3
4
5
6
7
<a class="..." id="..." data-modal="toggle" href="#">
Example link
</a>

<input class="form-control" type="text">

<img src="..." alt="...">

布尔(boolean)型属性

布尔型属性可以在声明时不赋值。XHTML 规范要求为其赋值,但是 HTML5 规范不需要。

更多信息请参考 WhatWG section on boolean attributes:

元素的布尔型属性如果有值,就是 true,如果没有值,就是 false。

如果一定要为其赋值的话,请参考 WhatWG 规范:

如果属性存在,其值必须是空字符串或 […] 属性的规范名称,并且不要再收尾添加空白符。

简单来说,就是不用赋值。

1
2
3
4
5
6
7
<input type="text" disabled>

<input type="checkbox" value="1" checked>

<select>
<option value="1" selected>1</option>
</select>

减少标签的数量

编写 HTML 代码时,尽量避免多余的父元素。很多时候,这需要迭代和重构来实现。请看下面的案例:

1
2
3
4
5
6
7

<span class="avatar">
<img src="...">
</span>


<img class="avatar" src="...">

JavaScript 生成的标签

通过 JavaScript 生成的标签让内容变得不易查找、编辑,并且降低性能。能避免时尽量避免。

CSS

语法

  • 用两个空格来代替制表符(tab) – 这是唯一能保证在所有环境下获得一致展现的方法。
  • 为选择器分组时,将单独的选择器单独放在一行。
  • 为了代码的易读性,在每个声明块的左花括号前添加一个空格。
  • 声明块的右花括号应当单独成行。
  • 每条声明语句的 : 后应该插入一个空格。
  • 为了获得更准确的错误报告,每条声明都应该独占一行。
  • 所有声明语句都应当以分号结尾。最后一条声明语句后面的分号是可选的,但是,如果省略这个分号,你的代码可能更易出错。
  • 对于以逗号分隔的属性值,每个逗号后面都应该插入一个空格(例如,box-shadow)。
  • 不要在 rgb()、rgba()、hsl()、hsla() 或 rect() 值的内部的逗号后面插入空格。这样利于从多个属性值(既加逗号也加空格)中区分多个颜色值(只加逗号,不加空格)。
  • 对于属性值或颜色参数,省略小于 1 的小数前面的 0 (例如,.5 代替 0.5;-.5px 代替 -0.5px)。
  • 十六进制值应该全部小写,例如,#fff。在扫描文档时,小写字符易于分辨,因为他们的形式更易于区分。
  • 尽量使用简写形式的十六进制值,例如,用 #fff 代替 #ffffff。
  • 为选择器中的属性添加双引号,例如,input[type="text"]。只有在某些情况下是可选的,但是,为了代码的一致性,建议都加上双引号。
  • 避免为 0 值指定单位,例如,用 margin: 0; 代替 margin: 0px;。

对于这里用到的术语有疑问吗?请参考 Wikipedia 上的 syntax section of the Cascading Style Sheets article。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/* Bad CSS */
.selector, .selector-secondary, .selector[type=text] {
padding:15px;
margin:0px 0px 15px;
background-color:rgba(0, 0, 0, 0.5);
box-shadow:0px 1px 2px #CCC,inset 0 1px 0 #FFFFFF
}

/* Good CSS */
.selector,
.selector-secondary,
.selector[type="text"] {
padding: 15px;
margin-bottom: 15px;
background-color: rgba(0,0,0,.5);
box-shadow: 0 1px 2px #ccc, inset 0 1px 0 #fff;
}

声明顺序

相关的属性声明应当归为一组,并按照下面的顺序排列:

  • Positioning
  • Box model
  • Typographic
  • Visual

由于定位(positioning)可以从正常的文档流中移除元素,并且还能覆盖盒模型(box model)相关的样式,因此排在首位。盒模型排在第二位,因为它决定了组件的尺寸和位置。

其他属性只是影响组件的*内部(inside)*或者是不影响前两组属性,因此排在后面。

完整的属性列表及其排列顺序请参考 Recess。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
.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;

/* Misc */
opacity: 1;
}

不要使用 @import

与 <link> 标签相比,@import 指令要慢很多,不光增加了额外的请求次数,还会导致不可预料的问题。替代办法有以下几种:

  • 使用多个 <link> 元素
  • 通过 Sass 或 Less 类似的 CSS 预处理器将多个 CSS 文件编译为一个文件
  • 通过 Rails、Jekyll 或其他系统中提供过 CSS 文件合并功能

请参考 Steve Souders 的文章了解更多知识。

1
2
3
4
5
6
7

<link rel="stylesheet" href="core.css">


<style>
@import url("more.css");
</style>

媒体查询(Media query)的位置

将媒体查询放在尽可能相关规则的附近。不要将他们打包放在一个单一样式文件中或者放在文档底部。如果你把他们分开了,将来只会被大家遗忘。下面给出一个典型的实例。

1
2
3
4
5
6
7
8
9
.element { ... }
.element-avatar { ... }
.element-selected { ... }

@media (min-width: 480px) {
.element { ...}
.element-avatar { ... }
.element-selected { ... }
}

带前缀的属性

当使用特定厂商的带有前缀的属性时,通过缩进的方式,让每个属性的值在垂直方向对齐,这样便于多行编辑。

在 Textmate 中,使用 Text → Edit Each Line in Selection (⌃⌘A)。在 Sublime Text 2 中,使用 Selection → Add Previous Line (⌃⇧↑) 和 Selection → Add Next Line (⌃⇧↓)。

1
2
3
4
5
/* Prefixed properties */
.selector {
-webkit-box-shadow: 0 1px 2px rgba(0,0,0,.15);
box-shadow: 0 1px 2px rgba(0,0,0,.15);
}

单行规则声明

对于只包含一条声明的样式,为了易读性和便于快速编辑,建议将语句放在同一行。对于带有多条声明的样式,还是应当将声明分为多行。

这样做的关键因素是为了错误检测 – 例如,CSS 校验器指出在 183 行有语法错误。如果是单行单条声明,你就不会忽略这个错误;如果是单行多条声明的话,你就要仔细分析避免漏掉错误了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
/* Single declarations on one line */
.span1 { width: 60px; }
.span2 { width: 140px; }
.span3 { width: 220px; }

/* Multiple declarations, one per line */
.sprite {
display: inline-block;
width: 16px;
height: 15px;
background-image: url(../img/sprite.png);
}
.icon { background-position: 0 0; }
.icon-home { background-position: 0 -20px; }
.icon-account { background-position: 0 -40px; }

简写形式的属性声明

在需要显示地设置所有值的情况下,应当尽量限制使用简写形式的属性声明。常见的滥用简写属性声明的情况如下:

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

大部分情况下,我们不需要为简写形式的属性声明指定所有值。例如,HTML 的 heading 元素只需要设置上、下边距(margin)的值,因此,在必要的时候,只需覆盖这两个值就可以。过度使用简写形式的属性声明会导致代码混乱,并且会对属性值带来不必要的覆盖从而引起意外的副作用。

MDN(Mozilla Developer Network)上一片非常好的关于 shorthand properties 的文章,对于不太熟悉简写属性声明及其行为的用户很有用。

1
2
3
4
5
6
7
8
9
10
11
12
13
 background: red;
background: url("image.jpg");
border-radius: 3px 3px 0 0;
}

/* Good example */
.element {
margin-bottom: 10px;
background-color: red;
background-image: url("image.jpg");
border-top-left-radius: 3px;
border-top-right-radius: 3px;
}

Less 和 Sass 中的嵌套

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

1
2
3
4
5
6
7
8
9
// Without nesting
.table > thead > tr > th { … }
.table > thead > tr > td { … }

// With nesting
.table > thead > tr {
> th { … }
> td { … }
}

注释

代码是由人编写并维护的。请确保你的代码能够自描述、注释良好并且易于他人理解。好的代码注释能够传达上下文关系和代码目的。不要简单地重申组件或 class 名称。

对于较长的注释,务必书写完整的句子;对于一般性注解,可以书写简洁的短语。

1
2
3
4
5
6
7
8
9
10
11
/* Bad example */
/* Modal header */
.modal-header {
...
}

/* Good example */
/* Wrapping element for .modal-title and .modal-close */
.modal-header {
...
}

class 命名

  • class 名称中只能出现小写字符和破折号(dashe)(不是下划线,也不是驼峰命名法)。破折号应当用于相关 class 的命名(类似于命名空间)(例如,.btn 和 .btn-danger)。
  • 避免过度任意的简写。.btn 代表 button,但是 .s 不能表达任何意思。
  • class 名称应当尽可能短,并且意义明确。
  • 使用有意义的名称。使用有组织的或目的明确的名称,不要使用表现形式(presentational)的名称。
  • 基于最近的父 class 或基本(base) class 作为新 class 的前缀。
  • 使用 .js-* class 来标识行为(与样式相对),并且不要将这些 class 包含到 CSS 文件中。

在为 Sass 和 Less 变量命名是也可以参考上面列出的各项规范。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
/* Bad example */
.t { ... }
.red { ... }
.header { ... }

/* Good example */
.tweet { ... }
.important { ... }
.tweet-header { ... }
~~~

## 选择器
* 对于通用元素使用 class ,这样利于渲染性能的优化。
* 对于经常出现的组件,避免使用属性选择器(例如,[class^="..."])。浏览器的性能会受到这些因素的影响。
* 选择器要尽可能短,并且尽量限制组成选择器的元素个数,建议不要超过 3 。
* **只有**在必要的时候才将 class 限制在最近的父元素内(也就是后代选择器)(例如,不使用带前缀的 class 时 -- 前缀类似于命名空间)。

扩展阅读:

* [Scope CSS classes with prefixes](http://markdotto.com/2012/02/16/scope-css-classes-with-prefixes/)
* [Stop the cascade](http://markdotto.com/2012/03/02/stop-the-cascade/)

```CSS
/* Bad example */
span { ... }
.page-container #stream .stream-item .tweet .tweet-header .username { ... }
.avatar { ... }

/* Good example */
.avatar { ... }
.tweet-header .username { ... }
.tweet .avatar { ... }

代码组织

  • 以组件为单位组织代码段。
  • 制定一致的注释规范。
  • 使用一致的空白符将代码分隔成块,这样利于扫描较大的文档。
  • 如果使用了多个 CSS 文件,将其按照组件而非页面的形式分拆,因为页面会被重组,而组件只会被移动。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
/*
* Component section heading
*/

.element { ... }


/*
* Component section heading
*
* Sometimes you need to include optional context for the entire component. Do that up here if it's important enough.
*/

.element { ... }

/* Contextual sub-component or modifer */
.element-heading { ... }

编辑器配置

将你的编辑器按照下面的配置进行设置,以避免常见的代码不一致和差异:

  • 用两个空格代替制表符(soft-tab 即用空格代表 tab 符)。
  • 保存文件时,删除尾部的空白符。
  • 设置文件编码为 UTF-8。
  • 在文件结尾添加一个空白行。

参照文档并将这些配置信息添加到项目的 editorconfig 文件中。例如:Bootstrap 中的 .editorconfig 实例。更多信息请参考 about EditorConfig。

<3

Heavily inspired by Idiomatic CSS and the GitHub Styleguide. Made with all the love in the world by @mdo.

0%