第一章、HTML5概述
1.6 HTML5的新功能
1.6.1 新的DOCTYPE和字符集
<!DOCTYPE html>
<meta charset="utf-8">
使用HTML5的DOCTYPE会触发浏览器以标准模式渲染显示页面
web页面有多种渲染模式,怪异模式(Quriks)、近标准模式(Almost Standards)以及标准模式(Standards)。浏览器会根据DOCTYPE识别该用哪种模式渲染页面。
1.6.2 新元素和旧元素
<article>
标签定义外部的内容。
比如来自一个外部的新闻提供者的一篇新的文章,或者来自 blog的文本,或者是来自论坛的文本。亦或是来自其他外部源内容,内容独立于文档的其余部分
<address>
标签定义文档作者或拥有者的联系信息。
通常的做法是将 address 元素添加到网页的头部或底部。
<aside>
标签定义主内容之外的内容。
aside 标签的内容应该与附近的内容相关。
<embed>
标签定义嵌入的内容,比如插件。
<fieldset>
标签会在相关表单元素周围绘制边框
<legend>
fieldset 元素定义标题(caption)。
<figure>
标签规定独立的流内容(图像、图表、照片、代码等等),用于对元素进行组合。
使用 figcaption元素为元素组添加标题。
<figcaption>
标签定义 figure 元素的标题。
figcaption元素应该被置于figure元素的第一个或最后一个子元素的位置。
<footer>
标签定义 section 或 document 的页脚。
它包含创作者的姓名、文档的创作日期以及联系信息。
<header>
标签定义 section 或 document 的页眉。
<hgroup>
标签用于对网页或区段(section)的标题进行组合。
<main>
元素中的内容对于文档来说应当是唯一的。
它不应包含在文档中重复出现的内容,比如侧栏、导航栏、版权信息、站点标志或搜索表单。IE不支持
PS:在一个文档中,不能出现一个以上的 <main>
元素。<main>
元素不能是以下元素的后代:<article>、<aside>、<footer>、<header>
或 <nav>
。
<mark>
主要用来在视觉上向用户呈现那些需要突出的文字。
比较典型的应用就是在搜索结果中向用户高亮显示搜索关键词。
<nav>
标签定义导航链接的部分。
<details>
标签定义元素的细节,用户可进行查看,或通过点击进行隐藏。与 legend 一起使用,来制作 detail 的标题。该标题对用户是可见的,当在其上点击时可打开或关闭 detail。
目前只有 Chrome 支持 details 标签。
<datalist>
标签定义可选数据的列表。
与 input 元素配合使用,就可以制作出输入值的下拉列表。
<section>
标签定义文档中的节(section、区段)。
比如章节、页眉、页脚或文档中的其他部分。
<summary>
标签包含 details 元素的标题,details 元素用于描述有关文档或文档片段的详细信息。
summary 元素应该是 details 元素的第一个子元素。
<time>
标签定义日期或时间,或者两者。
<audio>
标签象网页中插入声音,比如音乐或其他音频流。
<video>
标签定义视频,比如电影片段或其他视频流
<canvas>
标签定义图形,比如图表和其他图像。
这个 HTML元素是为了客户端矢量图形而设计的。它自己没有行为,但却把一个绘图 API 展现给客户端 JavaScript以使脚本能够把想绘制的东西都绘制到一块画布上。
<command>
标签定义命令按钮,比如单选按钮、复选框或按钮
<keygen>
标签定义生成密钥。
<meter>
标签定义度量衡。仅用于已知最大和最小值的度量。
必须定义度量的范围,既可以在元素的文本中,也可以在 min/max 属性中定义。
<output>
标签定义不同类型的输出,比如脚本的输出。
<progress>
标签运行中的进程。
可以使用progress标签来显示 JavaScript 中耗费时间的函数的进程。
HTML中所有自闭合的标签:
<br> <img> <input> <area> <base> <br> <col> <command> <embed> <hr> <keygen> <link>
<meta> <param> <source> <track> <wbr>
被移除的旧元素basefont
、big
、center
、font
、strike
、tt
,推荐用css处理更好
1.6.4 使用Selectors API简化选取操作
document.querySelector(".error"); //返回第一个.error
document.querySelectorAll(".error") //返回所有的.error
IE8及以上支持
第二章、Canvas API
2.2 使用HTML5 Canvas API
2.2.1 检测浏览器支持情况
<canvas id="drawing">Update your browser to enjoy canvas!</canvas>
<script type="text/javascript">
var drawing = document.getElementById('drawing');
//确定浏览器支持canvas
if(drawing.context){
//code
}
</script>
2.2.2 在页面中加入canvas
<canvas id="diagonal" style="border: 1px solid;" width="200" height="200"> </canvas>
<script>
function drawDiagonal() {
// Get the canvas element and its drawing context
var canvas = document.getElementById('diagonal');
//canvas中所有操作数通过上下文对象来完成的
var context = canvas.getContext('2d');
// Create a path in absolute coordinates
context.beginPath();
context.moveTo(70, 140);
context.lineTo(140, 70);
// Stroke the line onto the canvas
context.stroke();
}
window.addEventListener("load", drawDiagonal, true);
</script>
注意:使用canvas元素,必须先设置其width、height属性,其效果与在style中设置并不相同
Canvas 是一个画板和一张画纸,画板相当于一个容器,画图是在画纸上进行的,画板和画纸的默认宽高是300*150px
,当画纸与画板宽高相等时,图像不会被拉伸,当画纸与画板宽高不一样时,图像就会被拉伸(变形)。
style样式里设定的是仅画板的宽高,画纸的宽高还是为默认值300*150px
, 画纸不会让画板就这么空出一片,于是画纸连同图像就要一起拉伸到跟画板大小一样。所以就得到了变形之后的图片。
2.2.3 偏移
function drawDiagonal() {
var canvas = document.getElementById('diagonal');
var context = canvas.getContext('2d');
//在变换前保存context状态可方便以后恢复
context.save();
// Move the drawing context to the right, and down
context.translate(70, 140);
// Draw the same line as before, but using the origin as a start
context.beginPath();
context.moveTo(0, 0);
context.lineTo(70, -70);
context.stroke();
// 恢复context至原始状态
context.restore();
}
2.2.4 路径
beginPath() //开始绘制
moveTo(x,y) //将当前位置移动到新目标位置
lineTo(x,y) //从上一位置划线到新位置
closePath() //闭合路径
2.2.5 描边样式
lineWidth = value 设置线条宽度。
value
描述线段宽度的数字。 0、 负数、 Infinity 和 NaN 会被忽略。
lineCap = type 设置线条末端样式。
butt 线段末端以方形结束。
round 线段末端以圆形结束。
square 线段末端以方形结束,但是增加了一个宽度和线段相同,高度是线段厚度一半的矩形区域。
lineJoin = type 设定线条与线条间接合处的样式。
round
通过填充一个额外的,圆心在相连部分末端的扇形,绘制拐角的形状。 圆角的半径是线段的宽度。
bevel
在相连部分的末端填充一个额外的以三角形为底的区域, 每个部分都有各自独立的矩形拐角。
miter
通过延伸相连部分的外边缘,使其相交于一点,形成一个额外的菱形区域。这个设置可以通过 miterLimit 属性看到效果。
miterLimit = value
限制当两条线相交时交接处最大长度;所谓交接处长度(斜接长度)是指线条交接处内角顶点到外角顶点的长度。
value 斜接面限制比例的的数字。 0、负数、Infinity 和 NaN 都会被忽略。
getLineDash()返回一个包含当前虚线样式,长度为非负偶数的数组。
setLineDash(segments) 设置当前虚线样式。
lineDashOffset = value 设置虚线样式的起始偏移量。
2.2.6 填充样式
fillStyle = color 设置图形的填充颜色。
strokeStyle = color 设置图形轮廓的颜色。
context.strokeStyle = '#663300';
context.stroke(); //填充路径
context.fillStyle = '#339900';
context.fill(); //填充闭合路径内部像素点
context.fillStyle = '#663300';
context.fillRect(-5, -50, 10, 50); //填充矩形区域
2.2.7 绘制曲线
arc(x, y, radius, startAngle, endAngle, anticlockwise)
画一个以(x,y)为圆心的以radius为半径的圆弧(圆),从startAngle开始到endAngle结束,按照anticlockwise给定的方向(默认为顺时针)来生成。
arcTo(x1, y1, x2, y2, radius)
根据给定的控制点和半径画一段圆弧,再以直线连接两个控制点。
quadraticCurveTo(cp1x, cp1y, x, y)
绘制二次贝塞尔曲线,cp1x,cp1y为一个控制点,x,y为结束点。
bezierCurveTo(cp1x, cp1y, cp2x, cp2y, x, y)
绘制三次贝塞尔曲线,cp1x,cp1y为控制点一,cp2x,cp2y为控制点二,x,y为结束点。
2.2.9 在canvas中插入图片
var bark = new Image();
bark.src = "bark.jpg";
// 必须等到图片完全加载后才能对其操作
bark.onload = function () {
...
context.drawImage(bark, -5, -50, 10, 50);
...
}
2.2.10 渐变
createLinearGradient(x1, y1, x2, y2)
createLinearGradient 方法接受 4 个参数,表示渐变的起点 (x1,y1) 与终点 (x2,y2)。
createRadialGradient(x1, y1, r1, x2, y2, r2)
createRadialGradient 方法接受 6 个参数,前三个定义一个以 (x1,y1) 为原点,半径为 r1 的圆,后三个参数则定义另一个以 (x2,y2) 为原点,半径为 r2 的圆。
gradient.addColorStop(position, color)
addColorStop 方法接受 2 个参数,position 参数必须是一个 0.0 与 1.0 之间的数值,表示渐变中颜色所在的相对位置。例如,0.5 表示颜色会出现在正中间。color 参数必须是一个有效的 CSS 颜色值(如 #FFF, rgba(0,0,0,1),等等)。
// Create a 3 stop gradient horizontally across the trunk
var trunkGradient = context.createLinearGradient(-5, -50, 5, -50);
// The beginning of the trunk is medium brown
trunkGradient.addColorStop(0, '#663300');
// The middle-left of the trunnk is lighter in color
trunkGradient.addColorStop(0.4, '#996600');
// The right edge of the trunk is darkest
trunkGradient.addColorStop(1, '#552200');
// Apply the gradient as the fill style, and draw the trunk
context.fillStyle = trunkGradient;
context.fillRect(-5, -50, 10, 50);
2.2.11 使用图案样式
createPattern(image, type)
该方法接受两个参数。Image 可以是一个 Image 对象的引用,或者另一个 canvas 对象。Type 必须是下面的字符串值之一:repeat,repeat-x,repeat-y 和 no-repeat。
var gravel = new Image();
gravel.src = "gravel.jpg";
gravel.onload = function () {
...
context.strokeStyle = context.createPattern(gravel, 'repeat');
context.lineWidth = 20;
context.stroke();
...
}
2.2.12 缩放
scale(x, y)
scale 方法接受两个参数。x,y 分别是横轴和纵轴的缩放因子,它们都必须是正值。值比 1.0 小表示缩小,比 1.0 大则表示放大,值为 1.0 时什么效果都没有。
context.scale(2, 2);
2.2.13 旋转
rotate(angle)
这个方法只接受一个参数:旋转的角度(angle),它是顺时针方向的,以弧度为单位的值。
context.rotate(Math*PI/2);
2.2.14 文本
fillText(text, x, y [, maxWidth])
在指定的(x,y)位置填充指定的文本,绘制的最大宽度是可选的.
strokeText(text, x, y [, maxWidth])
在指定的(x,y)位置绘制文本边框,绘制的最大宽度是可选的.
context.textAlign = 'center';
context.fillText('Happy Trails!', 200, 60, 400);
2.2.15 阴影
shadowOffsetX = float
shadowOffsetX 和 shadowOffsetY 用来设定阴影在 X 和 Y 轴的延伸距离,它们是不受变换矩阵所影响的。负值表示阴影会往上或左延伸,正值则表示会往下或右延伸,它们默认都为 0。
shadowOffsetY = float
shadowOffsetX 和 shadowOffsetY 用来设定阴影在 X 和 Y 轴的延伸距离,它们是不受变换矩阵所影响的。负值表示阴影会往上或左延伸,正值则表示会往下或右延伸,它们默认都为 0。
shadowBlur = float
shadowBlur 用于设定阴影的模糊程度,其数值并不跟像素数量挂钩,也不受变换矩阵的影响,默认为 0。
shadowColor = color
shadowColor 是标准的 CSS 颜色值,用于设定阴影颜色效果,默认是全透明的黑色。
context.shadowOffsetX = 15;
context.shadowOffsetY = -10;
context.shadowBlur = 2;
第三章、SVG
3.1.5 在页面中添加SVG
<svg width="400" height="600"></svg>
3.1.7 变换SVG元素
<g>
元素代表“组”,可以用来结合多个相关元素
3.1.8 复用内容
<defs>
元素定义留待将来使用的内容
<use>
元素用于连接到<defs>
定义的内容
<svg width="200" height="200">
<defs>
<g id="ShapeGroup">
<rect x="10" y="20" width="100" height="80" stroke="red" fill="#ccc" />
</g>
</defs>
<use xlink:href="#ShapeGroup" transform="translate(60,0) scale(0.5)" />
<use xlink:href="#ShapeGroup" transform="translate(120,80) scale(0.4)" />
</svg>
3.1.9 图案和渐变
3.1.10 SVG路径
3.1.11 使用SVG文本
<svg width="200" height="200">
<text y="60" x="200" font-family="impact" font-size="60px" fill="#996600" text-anchor="middle">
Happy Trails!
</text>
</svg>
第四章、Audio and Video
4.2.1 浏览器支持性检测
<video src="vide.webm" controls>
Your browser does not suport HTML5 video.
</video>
4.2.3 理解媒体元素
4.2.3.3 媒体的控制
如果内置的空间不适用用户界面的布局,那么可以借助javascript函数和特性
函数 | 动作 |
---|---|
load() | 加载为播放做准备 |
play() | 加载并播放 |
pause() | 暂停播放 |
canPlayType(type) | 测试video元素是否支持给定的MIME类型的文件 |
第五章、Geolocation API
5.1 位置信息
HTML5 Geolocation API不指定设备使用哪种底层技术来定位应用程序的用户,只是用于检索位置信息的API
5.1.3 IP地址地理定位数据
基于IP地址的地理定位的实现方式是:自动查找用户IP地址,然后检索其注册的物理地址
5.1.4 GPS地理定位数据
GPS利用多个GPS卫星的信号实现,定位时间较长,不适合快速响应的应用程序
5.1.5 WI-FI地理定位数据
基于WI-FI的地理定位信息是通过三角距离计算得出的,这个三角距离指的是用户当前位置到已知的多个wi-fi接入点的距离
5.1.6 手机地理定位数据
通过用户嗲一些基站的三角距离确定的,可提供相当准确的位置信息
5.1.7 用户自定义的地理定位数据
5.4 使用HTML5 Geolocation API
执行HTML5 Geolocation的方式有很多,例如调用navigator.geolocation.getCurrentPosition()
function loadDemo() {
if(navigator.geolocation) {
document.getElementById("status").innerHTML = "HTML5 Geolocation is supported in your browser.";
navigator.geolocation.getCurrentPosition(updateLocation, handleLocationError,{timeout:10000});//调用位置信息
}
}
function updateLocation(position) {
var latitude = position.coords.latitude; //纬度
var longitude = position.coords.longitude; //经度
var accuracy = position.coords.accuracy; //准确度
var timestamp = position.timestamp;
if (!latitude || !longitude) {
document.getElementById("status").innerHTML =
"HTML5 Geolocation is supported in your browser, but your location is currently not available.";
return;
}
document.getElementById("latitude").innerHTML = "Latitude: " + latitude;
document.getElementById("longitude").innerHTML = "Longitude: " + longitude;
document.getElementById("accuracy").innerHTML = "Accuracy: " + accuracy + " meters";
document.getElementById("timestamp").innerHTML = "Timestamp: " + timestamp;
}
function handleLocationError(error) {
document.getElementById("status").style.background = "papayaWhip";
switch(error.code){
case 0:
updateStatus("There was an error while retrieving your location. Additional details: " + error.message);
break;
case 1:
updateStatus("The user opted not to share his or her location.");
break;
case 2:
updateStatus("The browser was unable to determine your location. Additional details: " + error.message);
break;
case 3:
updateStatus("The browser timed out before retrieving the location.");
break;
}
}
function updateStatus(message) {
document.getElementById("status").innerHTML = "<strong>Error</strong>: " + message;
}
第六章、Communication API
6.1 跨文档消息通信
跨文档消息通信可以确保iframe、标签页、窗口间安全的进行跨源通信
chatFrame.contentWindow.postMessage("hello world","http://www.example.com/");
6.1.3 使用postMessage API
- 浏览器支持情况检测
if(typeof window.postMessage === "undefined"){ //不支持postMessage }
- 发送消息
window.postMessage("hello world","portal.example.com");
- 监听消息事件
window.onmessage = function(e){ if(e.origin === ""){ //接收方可以接收特定源的消息 console.log(e.data) //打印接收数据 } }
<!-- http:localhost/test/index.html -->
<iframe id="iframe" src="http://127.0.0.1/test/a.html" style="display:none;"></iframe>
<script type="text/javascript">
window.onload = function() {
var iframe = document.getElementById("iframe");
iframe.contentWindow.postMessage("null", "http://127.0.0.1/test/a.html");
}
window.onmessage = function(e) {
if(e.origin === "http://127.0.0.1/a.html"){
document.write(e.data); //123 这里获取到了a页面的dom内容
}
}
</script>
<!-- http://127.0.0.1/test/a.html -->
<div id="test">123</div>
<script type="text/javascript">
window.onmessage = function(e) {
if(e.origin === "http:localhost/test/index.html"){
var text = document.getElementById('test').innerHTML;
//window.parent.postMessage()返回想要的数据
window.parent.postMessage(text, "http://localhost/test/index.html");
}
}
</script>
6.2 XMLHttpRequsest Level 2
XMLHttpRequsest Level 2的功能改进主要体现在:
- 跨源XMLHttpRequest;
- 进度事件(progress events)
6.2.1 跨源XMLHttpRequest
XMLHttpRequsest Level 2通过CORS实现了跨源XMLHttpRequest
跨源XMLHttpRequest请求包括一个origin头部
服务器端需要为请求的内容添加"Access-Control-Allow-Origin:"头部
6.2.2 进度事件
利用进度事件实现文件上传率
xhr.onprogress = function(e){
var total = e.total;
var loaded = e.loaded;
setProgress(radio + "% uploaded");
}
第七章、WebSockets API
WebSockets定义了双全工通信,大幅度减少了网络流量,并降低网络延迟 IE10+支持
7.3 使用 Web Sockets API
7.3.2 基本用法
为接受ws://loclahost:8080/echo上的链接,需要启动Python WebSocket服务器。
打开命令行窗口执行以下命令:python websocket.py
- Web Socket对象的创建及其与Web Socket服务器的连接
url = "ws://localhost:8080/echo"; w = new WebSocket(url);
- 添加事件监听器
w.onopen = function() { //建立连接触发open log("open"); w.send("thank you for accepting this Web Socket request"); } w.onmessage = function(e) { //收到消息触发message log(e.data.toString()); } w.onclose = function(e) { //链接关闭触发close log("closed"); } w.onerror = function(e) { //错误事件 log("error"); }
- 发送消息
document.getElementById("sendButton").onclick = function() { w.send(document.getElementById("inputMessage").value); }
第八章、Froms API
8.1 Froms API概述
HTML5表单包含了大量的新的API和元素类型
- 新的输入型控件
- 新的函数和特性
8.1.4 输入型控件
<input type="email" name="email">
type="email"的input输入类型用于表示语义上的e-mail地址输入域,在提交表单时,会自动验证 email 域的值。
[注意] IE9-浏览器及safari浏览器不支持
tel
<input type="tel" placeholder="请输入11位手机号码" pattern="\d{11}">
type="tel"的input输入类型用于表示语义上的电话输入域
search
<input type="search">
url
<input type="url" />
type="url"的input输入类型用于表示语义上的url地址的输入域,在提交表单时,会自动验证 url 域的值。
[注意]IE9-浏览器及safari浏览器不支持
number
<input type="number" min="0" max="10" step="0.5" value="6"/>
type="number"的input输入类型用于处理数字输入,step 规定合法的数字间隔
[注意]IE不支持该类型
range
<input type="range" min="0" max="10" step="0.5" value="6"/>
type="range"的input输入类型用于处理包含在一定范围内的数字输入
[注意]IE9-不支持该类型
color
<input type="color">
type="color"的input输入类型会创建一个调色板用来选择颜色,颜色值以URL编码后的十六进制数值提交。
如黑色会以%23000000发送,其中%23是#的URL编码
[注意]safari和IE不支持该类型
Date pickers
<input type="time" value="hh:mm:ss"><input type="month">
[注意]IE和firefox这种日期类型都不支持,chrome不支持datetime类型
8.2.1 新的表单特性和函数
placeholder
<input type="tel" placeholder="请输入11位手机号码">
placeholder 属性提供可描述输入字段预期值的提示信息(hint)。该提示会在输入字段为空时显示,并会在字段获得焦点时消失。
[注意]placeholder 属性适用于以下的 <input>
类型:text, search, url, tel, email 以及 password。
autocomplete
<form action="demo_form.asp" method="get" autocomplete="on">
Name:<input type="text" name="fname" /><br />
E-mail: <input type="email" name="email" autocomplete="off" /><br />
<input type="submit" />
</form>
autocomplete 属性规定表单是否应该启用自动完成功能。
自动完成允许浏览器预测对字段的输入。当用户在字段开始键入时,浏览器基于之前键入过的值,应该显示出在字段中填写的选项。
[注意]autocomplete 属性适用于 `
list 属性引用数据列表,其中包含输入字段的预定义选项。
min、max
<input type="number" name="points" min="0" max="10" />
max 属性规定输入字段所允许的最大值 max 属性与 min 属性配合使用,可创建合法值范围
[注意]max 和 min 属性适用于以下 <input>
类型:number, range, date, datetime, datetime-local, month, time 以及 week。
required
<input type="text" name="usr_name" required="required" />
required 属性规定必需在提交之前填写输入字段。如果使用该属性,则字段是必填(或必选)的。
[注意]required 属性适用于以下 <input>
类型:
text, search, url, tel, email, password, datepickers, number, checkbox, radio 以及 file。
step
<input type="number" name="points" step="3" />
step 属性规定输入字段的合法数字间隔(假如 step=“3”,则合法数字应该是 -3、0、3、6,以此类推)。
[注意]step、max 以及 min 属性适用于以下 <input>
类型:number, range, date, datetime, datetime-local, month, time 以及 week。
multiple
Select images: <input type="file" name="img" multiple="multiple" />
multiple 属性规定输入域中可选择多个值。
multiple 属性适用于以下类型的 input
标签:email 和 file。
pattern
<input type="text" name="country_code" pattern="[a-z]{3}" title="Three letter country code" />
pattern 属性规定用于验证输入字段的正则表达式模式。
[注意]pattern 属性适用于以下 <input>
类型:text, search, url, tel, email 以及 password 。
novalidate
<form action="demo_form.asp" novalidate="novalidate">
E-mail: <input type="email" name="user_email" />
<input type="submit" />
</form>
novalidate 属性规定当提交表单时不对其进行验证。如果使用该属性,则表单不会验证表单的输入。
[注意]novalidate 属性适用于:`