typora-root-url: pic
HTML5
一、简介
1、什么是 HTML5?
HTML5 是最新的 HTML 标准。
HTML5 是专门为承载丰富的 web 内容而设计的,并且无需额外插件。
HTML5 拥有新的语义、图形以及多媒体元素。
HTML5 提供的新元素和新的 API 简化了 web 应用程序的搭建。
HTML5 是跨平台的,被设计为在不同类型的硬件(PC、平板、手机、电视机等等)之上运行。
**注释:**在下面的章节中,您将学到如何“帮助”老版本的浏览器处理 HTML5。
2、HTML5 中的新内容
HTML5 的新的文档类型(DOCTYPE)声明非常简单:
1
2
3
4<!DOCTYPE html> The new character encoding (charset) declaration is also very simple: <meta charset="UTF-8">
实例:
1
2
3
4
5
6
7
8
9
10
11<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>Title of the document</title> </head> <body> Content of the document...... </body> </html>
**注释:**HTML5 中默认的字符编码是 UTF-8。
3、HTML5 - 新的属性语法
HTML5 标准允许 4 中不同的属性语法。
本例演示在 标签中使用的不同语法:
类型 | 示例 |
---|---|
Empty | <input type=“text” value=“John Doe” disabled> |
Unquoted | <input type=“text” value=John Doe> |
Double-quoted | <input type=“text” value=“John Doe”> |
Single-quoted | <input type=“text” value=‘John Doe’> |
在 HTML5 标准中,根据对属性的需求,可能会用到所有 4 种语法。
4、HTML5 - 新特性
HTML5 的一些最有趣的新特性:
- 新的语义元素,比如 <header>, <footer>, <article>, and <section>。
- 新的表单控件,比如数字、日期、时间、日历和滑块。
- 强大的图像支持(借由 <canvas> 和 <svg>)
- 强大的多媒体支持(借由 <video> 和 <audio>)
- 强大的新 API,比如用本地存储取代 cookie。
5、HTML5 - 已被删元素
以下 HTML 4.01 元素已从 HTML5 中删除:
- <acronym>
- <applet>
- <basefont>
- <big>
- <center>
- <dir>
- <font>
- <frame>
- <frameset>
- <noframes>
- <strike>
- <tt>
二、支持
1、浏览器支持
所有现代浏览器都支持 HTML5。
此外,所有浏览器,不论新旧,都会自动把未识别元素当做行内元素来处理。
正因如此,您可以帮助老式浏览器处理”未知的“ HTML 元素。
**注释:**您甚至可以教授石器时代的 IE6 如何处理未知的 HTML 元素。
2、将 HTML5 元素定义为块级元素
HTML5 定义了八个新的语义 HTML 元素。所有都是块级元素。
您可以把 CSS display 属性设置为 block,以确保老式浏览器中正确的行为:
实例:
1
2
3
4header, section, footer, aside, nav, main, article, figure { display: block; }
3、添加新元素
您可以通过浏览器 trick 向 HTML 添加任何新元素:
本例向 HTML 添加了一个名为 的新元素,并为其定义 display 样式:
实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21<!DOCTYPE html> <html> <head> <title>Creating an HTML Element</title> <script>document.createElement("myHero")</script> <style> myHero { display: block; background-color: #ddd; padding: 50px; font-size: 30px; } </style> </head> <body> <h1>My First Heading</h1> <p>My first paragraph.</p> <myHero>My First Hero</myHero> </body> </html>
已添加的 JavaScript 语句 document.createElement(“myHero”),仅适用于 IE。
4、Internet Explorer 的问题及解决方案
上述方案可用于所有新的 HTML5 元素,但是:
**注意:**Internet Explorer 8 以及更早的版本,不允许对未知元素添加样式。
幸运的是,Sjoerd Visscher 创造了 “HTML5 Enabling JavaScript”, “the shiv”:
1
2
3
4<!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->
以上代码是一段注释,但是 IE9 的早期版本会读取它(并理解它)。
5、完整的 Shiv 解决方案
实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18<!DOCTYPE html> <html> <head> <title>Styling HTML5</title> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]--> </head> <body> <h1>My First Article</h1> <article> London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants. </article> </body> </html>
引用 shiv 代码的链接必须位于 <head> 元素中,因为 Internet Explorer 需要在读取之前认识所有新元素。
6、HTML5 Skeleton
实例:
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<!DOCTYPE html> <html lang="en"> <head> <title>HTML5 Skeleton</title> <meta charset="utf-8"> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script> <![endif]--> <style> body {font-family: Verdana, sans-serif; font-size:0.8em;} header,nav, section,article,footer {border:1px solid grey; margin:5px; padding:8px;} nav ul {margin:0; padding:0;} nav ul li {display:inline; margin:5px;} </style> </head> <body> <header> <h1>HTML5 SKeleton</h1> </header> <nav> <ul> <li><a href="html5_semantic_elements.asp">HTML5 Semantic</a></li> <li><a href="html5_geolocation.asp">HTML5 Geolocation</a></li> <li><a href="html5_canvas.asp">HTML5 Graphics</a></li> </ul> </nav> <section> <h1>Famous Cities</h1> <article> <h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </article> <article> <h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </article> <article> <h2>Tokyo</h2> <p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.</p> </article> </section> <footer> <p>© 2014 W3Schools. All rights reserved.</p> </footer> </body> </html>
三、元素
1、新的语义/结构元素
HTML5 提供的新元素可以构建更好的文档结构:
标签 | 描述 |
---|---|
<article> | 定义文档内的文章。 |
<aside> | 定义页面内容之外的内容。 |
<bdi> | 定义与其他文本不同的文本方向。 |
<details> | 定义用户可查看或隐藏的额外细节。 |
<dialog> | 定义对话框或窗口。 |
<figcaption> | 定义 <figure> 元素的标题。 |
<figure> | 定义自包含内容,比如图示、图表、照片、代码清单等等。 |
<footer> | 定义文档或节的页脚。 |
<header> | 定义文档或节的页眉。 |
<main> | 定义文档的主内容。 |
<mark> | 定义重要或强调的内容。 |
<menuitem> | 定义用户能够从弹出菜单调用的命令/菜单项目。 |
<meter> | 定义已知范围(尺度)内的标量测量。 |
<nav> | 定义文档内的导航链接。 |
<progress> | 定义任务进度。 |
<rp> | 定义在不支持 ruby 注释的浏览器中显示什么。 |
<rt> | 定义关于字符的解释/发音(用于东亚字体)。 |
<ruby> | 定义 ruby 注释(用于东亚字体)。 |
<section> | 定义文档中的节。 |
<summary> | 定义 <details> 元素的可见标题。 |
<time> | 定义日期/时间。 |
<wbr> | 定义可能的折行(line-break)。 |
HTML5 <section> 元素
<section> 元素定义文档中的节。
根据 W3C 的 HTML 文献:“节(section)是有主题的内容组,通常具有标题”。
可以将网站首页划分为简介、内容、联系信息等节。
实例:
1
2
3
4
5<section> <h1>WWF</h1> <p>The World Wide Fund for Nature (WWF) is....</p> </section>
HTML5 <article> 元素
<article> 元素规定独立的自包含内容。
文档有其自身的意义,并且可以独立于网站其他内容进行阅读。
<article> 元素的应用场景:
- 论坛
- 博客
- 新闻
实例:
1
2
3
4
5
6<article> <h1>What Does WWF Do?</h1> <p>WWF's mission is to stop the degradation of our planet's natural environment, and build a future in which humans live in harmony with nature.</p> </article>
嵌套语义元素
在 HTML5 标准中,<article> 元素定义完整的相关元素自包含块。
<section> 元素被定义为相关元素块。
我们能够使用该定义来决定如何嵌套元素吗?不,我们不能!
在因特网上,您会发现 <section> 元素包含 <article> 元素的 HTML 页面,还有 <article> 元素包含 <sections> 元素的页面。
您还会发现 <section> 元素包含 <section> 元素,同时 <article> 元素包含 <article> 元素。
HTML5 <header> 元素
<header> 元素为文档或节规定页眉
一个文档中可以有多个
元素。 下例为一篇文章定义了页眉:
实例:
1
2
3
4
5
6
7
8
9<article> <header> <h1>What Does WWF Do?</h1> <p>WWF's mission:</p> </header> <p>WWF's mission is to stop the degradation of our planet's natural environment, and build a future in which humans live in harmony with nature.</p> </article>
HTML5 <footer> 元素
<footer> 元素为文档或节规定页脚。
<footer> 元素应该提供有关其包含元素的信息。
页脚通常包含文档的作者、版权信息、使用条款链接、联系信息等等。
您可以在一个文档中使用多个 <footer> 元素。
实例:
1
2
3
4
5
6<footer> <p>Posted by: Hege Refsnes</p> <p>Contact information: <a href="mailto:someone@example.com"> someone@example.com</a>.</p> </footer>
HTML5 <nav> 元素
<nav> 元素定义导航链接集合。
<nav> 元素旨在定义大型的导航链接块。不过,并非文档中所有链接都应该位于 <nav> 元素中!
实例:
1
2
3
4
5
6
7<nav> <a href="/html/">HTML</a> | <a href="/css/">CSS</a> | <a href="/js/">JavaScript</a> | <a href="/jquery/">jQuery</a> </nav>
HTML5 <aside> 元素
<aside> 元素页面主内容之外的某些内容(比如侧栏)。
aside 内容应该与周围内容相关。
实例:
1
2
3
4
5
6<p>My family and I visited The Epcot center this summer.</p> <aside> <h4>Epcot Center</h4> <p>The Epcot Center is a theme park in Disney World, Florida.</p> </aside>
HTML5 <figure> 和 <figcaption> 元素
在书籍和报纸中,与图片搭配的标题很常见。
标题(caption)的作用是为图片添加可见的解释。
通过 HTML5,图片和标题能够被组合在 <figure> 元素中:
实例:
1
2
3
4
5<figure> <img src="pic_mountain.jpg" alt="The Pulpit Rock" width="304" height="228"> <figcaption>Fig1. - The Pulpit Pock, Norway.</figcaption> </figure>
<img> 元素定义图像,<figcaption> 元素定义标题。
2、新的表单元素
标签 | 描述 |
---|---|
<datalist> | 定义输入控件的预定义选项。 |
<keygen> | 定义键对生成器字段(用于表单)。 |
<output> | 定义计算结果。 |
3、新的输入类型
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZreG9oQg-1653830778572)(/image-20211122231239407.png)]
4、新的属性语法
HTML5 允许四种不同的属性语法。
该例演示 <input> 标签中使用的不同语法:
标签 | 描述 |
---|---|
Empty | <input type=“text” value=“John Doe” disabled> |
Unquoted | <input type=“text” value=John> |
Double-quoted | <input type=“text” value=“John Doe”> |
Single-quoted | <input type=“text” value=‘John Doe’> |
在 HTML5 中,根据属性所需,可能会使用所有这四种语法。
5、图像
标签 | 描述 |
---|---|
<canvas> | 定义使用 JavaScript 的图像绘制。 |
<svg> | 定义使用 SVG 的图像绘制。 |
canvas 元素:
1
2
3
4<canvas id="myCanvas" width="244" height="182" style="border:1px solid #d3d3d3;"> Your browser does not support the HTML5 canvas tag. </canvas>
在 HTML5 中,您能够将 SVG 元素直接嵌入 HTML 页面中:
实例:
1
2
3
4
5
6
7
8
9
10<!DOCTYPE html> <html> <body> <svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190"> <polygon points="100,10 40,180 190,60 10,60 160,180" style="fill:lime;stroke:purple;stroke-width:5;fill-rule:evenodd;" /> </svg> </body> </html>
6、新的媒介元素
标签 | 描述 |
---|---|
<audio> | 定义声音或音乐内容。 |
<embed> | 定义外部应用程序的容器(比如插件)。 |
<source> | 定义 <video> 和 <audio> 的来源。 |
<track> | 定义 <video> 和 <audio> 的轨道。 |
<video> | 定义视频或影片内容。 |
四、迁移
1、从 HTML4 迁移至 HTML5
注释:您可以使用相同的技巧从 HTML4 以及 XHTML 迁移至 HTML5。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-vrmCPcXr-1653830778573)(/image-20211122232653410.png)]
实例对比:
典型的 HTML4 页面
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<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=utf-8"> <title>HTML4</title> <style> body {font-family:Verdana,sans-serif;font-size:0.8em;} div#header,div#footer,div#content,div#post {border:1px solid grey;margin:5px;margin-bottom:15px;padding:8px;background-color:white;} div#header,div#footer {color:white;background-color:#444;margin-bottom:5px;} div#content {background-color:#ddd;} div#menu ul {margin:0;padding:0;} div#menu ul li {display:inline; margin:5px;} </style> </head> <body> <div id="header"> <h1>Monday Times</h1> </div> <div id="menu"> <ul> <li>News</li> <li>Sports</li> <li>Weather</li> </ul> </div> <div id="content"> <h2>News Section</h2> <div id="post"> <h2>News Article</h2> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> </div> <div id="post"> <h2>News Article</h2> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> </div> </div> <div id="footer"> <p>© 2014 Monday Times. All rights reserved.</p> </div> </body> </html>
典型的 HTML5 页面
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<!DOCTYPE html> <html lang="en"> <title>HTML5</title> <meta charset="utf-8"> <!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"> </script> <![endif]--> <style> body { font-family:Verdana,sans-serif;font-size:0.8em; } header,footer,section,article { border:1px solid grey; margin:5px;margin-bottom:15px;padding:8px; background-color:white; } header,footer { color:white;background-color:#444;margin-bottom:5px; } section { background-color:#ddd; } nav ul { margin:0;padding:0; } nav ul li { display:inline; margin:5px; } </style> <body> <header> <h1>Monday Times</h1> </header> <nav> <ul> <li>News</li> <li>Sports</li> <li>Weather</li> </ul> </nav> <section> <h2>News Section</h2> <div id="post"> <h2>News Article</h2> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> </div> <div id="post"> <h2>News Article</h2> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> </div> </section> <footer> <p>© 2014 Monday Times. All rights reserved.</p> </footer> </body> </html>
2、更改为 HTML5 Doctype
修改文档类型,从 HTML4 doctype:
1
2
3<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
修改为 HTML5 doctype:
1
2<!DOCTYPE html>
3、更改为 HTML5 编码
修改编码信息,从 HTML4:
1
2<meta http-equiv="Content-Type" content="text/html;charset=utf-8">
改为 HTML5:
1
2<meta charset="utf-8">
4、添加 shiv
所有现代浏览器都支持 HTML5 语义元素。
此外,您可以“教授”老式浏览器如何处理“未知元素”。
为 Internet Explorer 支持而添加的 shiv:
1
2
3
4<!--[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <![endif]-->
5、为 HTML5 语义元素添加 CSS
请看已有的 CSS 样式:
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
33div#header,div#footer,div#content,div#post { border:1px solid grey;margin:5px;margin-bottom:15px;padding:8px;background-color:white; } div#header,div#footer { color:white;background-color:#444;margin-bottom:5px; } div#content { background-color:#ddd; } div#menu ul { margin:0;padding:0; } div#menu ul li { display:inline; margin:5px; } Duplicate with equal CSS styles for HTML5 semantic elements: header,footer,section,article { border:1px solid grey;margin:5px;margin-bottom:15px;padding:8px;background-color:white; } header,footer { color:white;background-color:#444;margin-bottom:5px; } section { background-color:#ddd; } nav ul { margin:0;padding:0; } nav ul li { display:inline; margin:5px; }
6、更改为 HTML5 < header> 和 < footer>
把 id=“header” 和 id=“footer” 的 <div> 元素:
1
2
3
4
5
6
7
8
9
10<div id="header"> <h1>Monday Times</h1> </div> . . . <div id="footer"> <p>© 2014 W3Schools. All rights reserved.</p> </div>
修改为 HTML5 语义元素 <header> 和 <footer>:
1
2
3
4
5
6
7
8
9
10<header> <h1>Monday Times</h1> </header> . . . <footer> <p>© 2014 W3Schools. All rights reserved.</p> </footer>
7、更改为 HTML5 <nav>
把 id=“menu” 的 <div> 元素:
1
2
3
4
5
6
7
8<div id="menu"> <ul> <li>News</li> <li>Sports</a></li> <li>Weather</li> </ul> </div>
修改为 HTML5 语义元素 <nav>:
1
2
3
4
5
6
7
8<nav> <ul> <li>News</li> <li>Sports</a></li> <li>Weather</li> </ul> </nav>
8、更改为 HTML5 <section>
把 id=“content” 的 the <div> 元素:
1
2
3
4
5
6<div id="content"> . . . </div>
修改为 HTML5 语义元素 <section>:
1
2
3
4
5
6<section> . . . </section>
9、更改为 HTML5 <article>
把 class=“post” 的所有 <div> 元素:
1
2
3
4
5
6<div class="post"> <h2>News Article</h2> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> </div>
修改为 HTML5 语义元素 <article>:
1
2
3
4
5
6<article> <h2>News Article</h2> <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum.</p> </article>
10、<article> <section> 与 <div> 之间的差异
在 HTML5 标准中,<article> <section> 与 <div> 之间的差异很小,令人困惑。
在 HTML5 标准中,<section> 元素被定位为相关元素的块。
<article> 元素被定义为相关元素的完整的自包含块。
元素被定义为子元素的块。如何理解呢?
在上面的例子中,我们曾使用 <section> 作为相关 <articles> 的容器。
但是,我们也能够把 <article> 用作文章的容器。
下面是一些不同的例子:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<article> 中的 <article>: <article> <h2>Famous Cities</h2> <article> <h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </article> <article> <h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </article> <article> <h2>Tokyo</h2> <p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.</p> </article> </article>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19<article> 中的 <div>: <article> <h2>Famous Cities</h2> <div class="city"> <h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </div> <div class="city"> <h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </div> <div class="city"> <h2>Tokyo</h2> <p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.</p> </div> </article>
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<article> 中的 <section> 中的 <div>: <article> <section> <h2>Famous Cities</h2> <div class="city"> <h2>London</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </div> <div class="city"> <h2>Paris</h2> <p>Paris is the capital and most populous city of France.</p> </div> <div class="city"> <h2>Tokyo</h2> <p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.</p> </div> </section> <section> <h2>Famous Countries</h2> <div class="country"> <h2>England</h2> <p>London is the capital city of England. It is the most populous city in the United Kingdom, with a metropolitan area of over 13 million inhabitants.</p> </div> <div class="country"> <h2>France</h2> <p>Paris is the capital and most populous city of France.</p> </div> <div class="country"> <h2>Japan</h2> <p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area, and the most populous metropolitan area in the world.</p> </div> </section> </article>
HTML5 API
一、地理定位
HTML5 Geolocation(地理定位)用于定位用户的位置。
实例:
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<!DOCTYPE html> <html> <body> <p id="demo">点击这个按钮,获得您的位置:</p> <button onclick="getLocation()">试一下</button> <div id="mapholder"></div> <script src="http://maps.google.com/maps/api/js?sensor=false"></script> <script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition,showError); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { lat=position.coords.latitude; lon=position.coords.longitude; latlon=new google.maps.LatLng(lat, lon) mapholder=document.getElementById('mapholder') mapholder.style.height='250px'; mapholder.style.width='500px'; var myOptions={ center:latlon,zoom:14, mapTypeId:google.maps.MapTypeId.ROADMAP, mapTypeControl:false, navigationControlOptions:{style:google.maps.NavigationControlStyle.SMALL} }; var map=new google.maps.Map(document.getElementById("mapholder"),myOptions); var marker=new google.maps.Marker({position:latlon,map:map,title:"You are here!"}); } function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML="User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML="Location information is unavailable." break; case error.TIMEOUT: x.innerHTML="The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML="An unknown error occurred." break; } } </script> </body> </html>
1、定位用户的位置
HTML5 Geolocation API 用于获得用户的地理位置。
鉴于该特性可能侵犯用户的隐私,除非用户同意,否则用户位置信息是不可用的。
2、浏览器支持
Internet Explorer 9、Firefox、Chrome、Safari 以及 Opera 支持地理定位。
**注释:**对于拥有 GPS 的设备,比如 iPhone,地理定位更加精确。
3、HTML5 - 使用地理定位
请使用 getCurrentPosition() 方法来获得用户的位置。
下例是一个简单的地理定位实例,可返回用户位置的经度和纬度。
实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.getCurrentPosition(showPosition); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; } </script>
例子解释:
- 检测是否支持地理定位
- 如果支持,则运行 getCurrentPosition() 方法。如果不支持,则向用户显示一段消息。
- 如果getCurrentPosition()运行成功,则向参数showPosition中规定的函数返回一个coordinates对象
- showPosition() 函数获得并显示经度和纬度
上面的例子是一个非常基础的地理定位脚本,不含错误处理。
4、处理错误和拒绝
getCurrentPosition() 方法的第二个参数用于处理错误。它规定当获取用户位置失败时运行的函数:
实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19function showError(error) { switch(error.code) { case error.PERMISSION_DENIED: x.innerHTML="User denied the request for Geolocation." break; case error.POSITION_UNAVAILABLE: x.innerHTML="Location information is unavailable." break; case error.TIMEOUT: x.innerHTML="The request to get user location timed out." break; case error.UNKNOWN_ERROR: x.innerHTML="An unknown error occurred." break; } }
错误代码:
- Permission denied - 用户不允许地理定位
- Position unavailable - 无法获取当前位置
- Timeout - 操作超时
5、在地图中显示结果
如需在地图中显示结果,您需要访问可使用经纬度的地图服务,比如谷歌地图或百度地图:
实例:
1
2
3
4
5
6
7
8function showPosition(position) { var latlon=position.coords.latitude+","+position.coords.longitude; var img_url="http://maps.googleapis.com/maps/api/staticmap?center=" +latlon+"&zoom=14&size=400x300&sensor=false"; document.getElementById("mapholder").innerHTML="<img src='"+img_url+"' />"; }
在上例中,我们使用返回的经纬度数据在谷歌地图中显示位置(使用静态图像)。
6、给定位置的信息
本页演示的是如何在地图上显示用户的位置。不过,地理定位对于给定位置的信息同样很有用处。
案例:
- 更新本地信息
- 显示用户周围的兴趣点
- 交互式车载导航系统 (GPS)
7、getCurrentPosition() 方法 - 返回数据
若成功,则 getCurrentPosition() 方法返回对象。始终会返回 latitude、longitude 以及 accuracy 属性。如果可用,则会返回其他下面的属性。
属性 | 描述 |
---|---|
coords.latitude | 十进制数的纬度 |
coords.longitude | 十进制数的经度 |
coords.accuracy | 位置精度 |
coords.altitude | 海拔,海平面以上以米计 |
coords.altitudeAccuracy | 位置的海拔精度 |
coords.heading | 方向,从正北开始以度计 |
coords.speed | 速度,以米/每秒计 |
timestamp | 响应的日期/时间 |
8、Geolocation 对象 - 其他有趣的方法
watchPosition() - 返回用户的当前位置,并继续返回用户移动时的更新位置(就像汽车上的 GPS)。
clearWatch() - 停止 watchPosition() 方法
下面的例子展示 watchPosition() 方法。您需要一台精确的 GPS 设备来测试该例(比如 iPhone):
实例:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17<script> var x=document.getElementById("demo"); function getLocation() { if (navigator.geolocation) { navigator.geolocation.watchPosition(showPosition); } else{x.innerHTML="Geolocation is not supported by this browser.";} } function showPosition(position) { x.innerHTML="Latitude: " + position.coords.latitude + "<br />Longitude: " + position.coords.longitude; } </script>
二、拖放
1、拖放
拖放(Drag 和 Drop)是很常见的特性。它指的是您抓取某物并拖入不同的位置。
拖放是 HTML5 标准的组成部分:任何元素都是可拖放的。
2、浏览器支持
表格中的数字指示了完全支持拖放的首个浏览器版本。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-KVG2YrGH-1653830778574)(/image-20211123000055964.png)]
3、HTML 拖放实例
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23<!DOCTYPE HTML> <html> <head> <script> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); } function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div> <img id="drag1" src="img_logo.gif" draggable="true" ondragstart="drag(event)" width="336" height="69"> </body> </html>
它也许看上去有点复杂,不过让我们研究一下拖放事件的所有不同部分。
4、把元素设置为可拖放
首先:为了把一个元素设置为可拖放,请把 draggable 属性设置为 true:
1
2<img draggable="true">
5、拖放的内容 - ondragstart 和 setData()
然后,规定当元素被拖动时发生的事情。
在上面的例子中,ondragstart 属性调用了一个 drag(event) 函数,规定拖动什么数据。
dataTransfer.setData() 方法设置被拖动数据的数据类型和值:
1
2
3
4function drag(ev) { ev.dataTransfer.setData("text", ev.target.id); }
在本例中,数据类型是 “text”,而值是这个可拖动元素的 id (“drag1”)。
6、拖到何处 - ondragover
ondragover 事件规定被拖动的数据能够被放置到何处。
默认地,数据/元素无法被放置到其他元素中。为了实现拖放,我们必须阻止元素的这种默认的处理方式。
这个任务由 ondragover 事件的 event.preventDefault() 方法完成:
1
2event.preventDefault()
7、进行放置 - ondrop
当放开被拖数据时,会发生 drop 事件。
在上面的例子中,ondrop 属性调用了一个函数,drop(event):
1
2
3
4
5
6function drop(ev) { ev.preventDefault(); var data = ev.dataTransfer.getData("text"); ev.target.appendChild(document.getElementById(data)); }
代码解释:
- 调用 preventDefault() 来阻止数据的浏览器默认处理方式(drop 事件的默认行为是以链接形式打开)
- 通过 dataTransfer.getData() 方法获得被拖的数据。该方法将返回在 setData() 方法中设置为相同类型的任何数据
- 被拖数据是被拖元素的 id (“drag1”)
- 把被拖元素追加到放置元素中
8、更多实例
来回拖放图片
如何在两个
元素之间来回拖放图像:
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<!DOCTYPE HTML> <html> <head> <style type="text/css"> #div1, #div2 {float:left; width:198px; height:66px; margin:10px;padding:10px;border:1px solid #aaaaaa;} </style> <script type="text/javascript"> function allowDrop(ev) { ev.preventDefault(); } function drag(ev) { ev.dataTransfer.setData("Text",ev.target.id); } function drop(ev) { ev.preventDefault(); var data=ev.dataTransfer.getData("Text"); ev.target.appendChild(document.getElementById(data)); } </script> </head> <body> <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"> <img src="/i/eg_dragdrop_w3school.gif" draggable="true" ondragstart="drag(event)" id="drag1" /> </div> <div id="div2" ondrop="drop(event)" ondragover="allowDrop(event)"></div> </body> </html>
三、Web存储
1、什么是 HTML 本地存储?
通过本地存储(Local Storage),web 应用程序能够在用户浏览器中对数据进行本地的存储。
在 HTML5 之前,应用程序数据只能存储在 cookie 中,包括每个服务器请求。本地存储则更安全,并且可在不影响网站性能的前提下将大量数据存储于本地。
与 cookie 不同,存储限制要大得多(至少5MB),并且信息不会被传输到服务器。
本地存储经由起源地(origin)(经由域和协议)。所有页面,从起源地,能够存储和访问相同的数据。
2、浏览器支持
表格中的数组指示了完全支持本地存储的首个浏览器版本。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-7DlX9ktn-1653830778575)(/1637661110(1)].jpg)
3、HTML 本地存储对象
HTML 本地存储提供了两个在客户端存储数据的对象:
- window.localStorage - 存储没有截止日期的数据
- window.sessionStorage - 针对一个 session 来存储数据(当关闭浏览器标签页时数据会丢失)
在使用本地存储时,请检测 localStorage 和 sessionStorage 的浏览器支持:
1
2
3
4
5
6if (typeof(Storage) !== "undefined") { // 针对 localStorage/sessionStorage 的代码 } else { // 抱歉!不支持 Web Storage .. }
4、localStorage 对象
localStorage 对象存储的是没有截止日期的数据。当浏览器被关闭时数据不会被删除,在下一天、周或年中,都是可用的。
实例:
1
2
3
4
5// 存储 localStorage.setItem("lastname", "Gates"); // 取回 document.getElementById("result").innerHTML = localStorage.getItem("lastname");
实例解释:
- 创建 localStorage 名称/值对,其中:name=“lastname”,value=“Gates”
- 取回 “lastname” 的值,并把它插到 id=“result” 的元素中
上例也可这样写:
1
2
3
4
5// 存储 localStorage.lastname = "Gates"; // 取回 document.getElementById("result").innerHTML = localStorage.lastname;
删除 “lastname” localStorage 项目的语法如下:
1
2localStorage.removeItem("lastname");
**注释:**名称/值对始终存储为字符串。如果需要请记得把它们转换为其他格式!
下面的例子对用户点击按钮的次数进行计数。在代码中,值字符串被转换为数值,依次对计数进行递增:
1
2
3
4
5
6
7
8if (localStorage.clickcount) { localStorage.clickcount = Number(localStorage.clickcount) + 1; } else { localStorage.clickcount = 1; } document.getElementById("result").innerHTML = "您已经点击这个按钮 " + localStorage.clickcount + " 次。";
5、sessionStorage 对象
sessionStorage 对象等同 localStorage 对象,不同之处在于只对一个 session 存储数据。如果用户关闭具体的浏览器标签页,数据也会被删除。
下例在当前 session 中对用户点击按钮进行计数:
实例:
1
2
3
4
5
6
7
8if (sessionStorage.clickcount) { sessionStorage.clickcount = Number(sessionStorage.clickcount) + 1; } else { sessionStorage.clickcount = 1; } document.getElementById("result").innerHTML = "在本 session 中,您已经点击这个按钮 " + sessionStorage.clickcount + " 次。";
四、应用缓存
1、什么是应用程序缓存?
HTML5 引入了应用程序缓存(Application Cache),这意味着可对 web 应用进行缓存,并可在没有因特网连接时进行访问。
应用程序缓存为应用带来三个优势:
- 离线浏览 - 用户可在应用离线时使用它们
- 速度 - 已缓存资源加载得更快
- 减少服务器负载 - 浏览器将只从服务器下载更新过或更改过的资源
2、浏览器支持
表格中的数字指示完全支持应用程序缓存的首个浏览器版本。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-m3bGStfR-1653830778576)(/image-20211123000055964.png)]
3、HTML Cache Manifest 实例
下例展示了带有 cache manifest 的 HTML 文档(供离线浏览):
1
2
3
4
5
6
7<!DOCTYPE HTML> <html manifest="demo.appcache"> <body> 文档内容 ...... </body> </html>
4、Cache Manifest 基础
如需启用应用程序缓存,请在文档的 标签中包含 manifest 属性:
1
2
3
4
5<!DOCTYPE HTML> <html manifest="demo.appcache"> ... </html>
每个指定了 manifest 的页面在用户对其访问时都会被缓存。如果未指定 manifest 属性,则页面不会被缓存(除非在 manifest 文件中直接指定了该页面)。
manifest 文件的建议文件扩展名是:“.appcache”。
**注意:**manifest 文件需要设置正确的 MIME-type,即 “text/cache-manifest”。必须在 web 服务器上进行配置。
5、Manifest 文件
manifest 文件是简单的文本文件,它告知浏览器被缓存的内容(以及不缓存的内容)。
manifest 文件有三个部分:
- CACHE MANIFEST - 在此标题下列出的文件将在首次下载后进行缓存
- NETWORK - 在此标题下列出的文件需要与服务器的连接,且不会被缓存
- FALLBACK - 在此标题下列出的文件规定当页面无法访问时的回退页面(比如 404 页面)
6、CACHE MANIFEST
第一行,CACHE MANIFEST,是必需的:
1
2
3
4
5CACHE MANIFEST /theme.css /logo.gif /main.js
上面的 manifest 文件列出了三个资源:一个 CSS 文件,一个 GIF 图像,以及一个 JavaScript 文件。当 manifest 文件被加载后,浏览器会从网站的根目录下载这三个文件。然后,无论用户何时与因特网断开连接,这些资源依然可用。
7、NETWORK
下面的 NETWORK 部分规定文件 “login.php” 永远不会被缓存,且离线时是不可用的:
1
2
3NETWORK: login.asp
可以使用星号来指示所有其他其他资源/文件都需要因特网连接:
1
2
3
4NETWORK: * FALLBACK
下面的 FALLBACK 部分规定如果无法建立因特网连接,则用 “offline.html” 替代 /html/ 目录中的所有文件:
1
2
3FALLBACK: /html/ /offline.html
**注释:**第一个 URI 是资源,第二个是替补。
8、更新缓存
一旦应用被缓存,它就会保持缓存直到发生下列情况:
- 用户清空浏览器缓存
- manifest 文件被修改(参阅下面的提示)
- 由程序来更新应用缓存
9、实例 - 完整的 Cache Manifest 文件
1
2
3
4
5
6
7
8
9
10CACHE MANIFEST # 2012-02-21 v1.0.0 /theme.css /logo.gif /main.js NETWORK: login.asp FALLBACK: /html/ /offline.html
**提示:**以 “#” 开头的是注释行,但也可满足其他用途。应用的缓存只会在其 manifest 文件改变时被更新。如果您编辑了一幅图像,或者修改了一个 JavaScript 函数,这些改变都不会被重新缓存。更新注释行中的日期和版本号是一种使浏览器重新缓存文件的办法。
10、关于应用程序缓存的注意事项
请留心缓存的内容。
一旦文件被缓存,则浏览器会继续展示已缓存的版本,即使您修改了服务器上的文件。为了确保浏览器更新缓存,您需要更新 manifest 文件。
**注释:**浏览器对缓存数据的容量限制可能不太一样(某些浏览器的限制是每个站点 5MB)。
五、Web Workers
1、什么是 Web Worker?
当在 HTML 页面中执行脚本时,页面是不可响应的,直到脚本已完成。
Web worker 是运行在后台的 JavaScript,独立于其他脚本,不会影响页面的性能。您可以继续做任何愿意做的事情:点击、选取内容等等,而此时 web worker 运行在后台。
2、浏览器支持
表格中的数字指示完全支持 Web Worker 的首个浏览器版本。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-pwfDPbpc-1653830778577)(/image-20211123001928765.png)]
3、HTML Web Workers 实例
下面的例子创建了一个简单的 web worker,在后台计数:
计数:
启动 Worker | 停止 Worker
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<!DOCTYPE html> <html> <body> <p>计数: <output id="result"></output></p> <button onclick="startWorker()">开始 Worker</button> <button onclick="stopWorker()">停止 Worker</button> <br /><br /> <script> var w; function startWorker() { if(typeof(Worker)!=="undefined") { if(typeof(w)=="undefined") { w=new Worker("/example/html5/demo_workers.js"); } w.onmessage = function (event) { document.getElementById("result").innerHTML=event.data; }; } else { document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers..."; } } function stopWorker() { w.terminate(); } </script> </body> </html>
4、检测 Web Worker 支持
在创建 web worker 之前,请检测用户浏览器是否支持它:
1
2
3
4
5
6
7if (typeof(Worker) !== "undefined") { // 是的!支持 Web worker! // 一些代码..... } else { // 抱歉!不支持 Web Worker! }
5、创建 Web Worker 文件
现在,让我们在一个外部 JavaScript 文件中创建我们的 web worker。
在此处,我们创建了计数脚本。该脚本存储于 “demo_workers.js” 文件中:
1
2
3
4
5
6
7
8var i = 0; function timedCount() { i = i + 1; postMessage(i); setTimeout("timedCount()",500); } timedCount();
以上代码中重要的部分是 postMessage() 方法 - 它用于向 HTML 页面传回一段消息。
注释: web worker 通常不用于如此简单的脚本,而是用于更耗费 CPU 资源的任务。
6、创建 Web Worker 对象
现在我们已经有了 web worker 文件,我们需要从 HTML 页面调用它。
下面的代码行检测是否存在 worker,如果不存在,- 它会创建一个新的 web worker 对象,然后运行 “demo_workers.js” 中的代码:
1
2
3
4if (typeof(w) == "undefined") { w = new Worker("demo_workers.js"); }
然后我们就可以从 web worker 发生和接收消息了。
向 web worker 添加一个 “onmessage” 事件监听器:
1
2
3
4w.onmessage = function(event){ document.getElementById("result").innerHTML = event.data; };
当 web worker 传送消息时,会执行事件监听器中的代码。来自 web worker 的数据会存储于 event.data 中。
7、终止 Web Worker
当创建 web worker 后,它会继续监听消息(即使在外部脚本完成后)直到其被终止为止。
如需终止 web worker,并释放浏览器/计算机资源,请使用 terminate() 方法:
1
2w.terminate();
8、复用 Web Worker
如果您把 worker 变量设置为 undefined,在其被终止后,可以重复使用该代码:
1
2w = undefined;
9、完整的 Web Worker 实例代码
我们已经看到了 .js 文件中的 Worker 代码。下面是 HTML 页面的代码:
实例:
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<!DOCTYPE html> <html> <body> <p>Count numbers: <output id="result"></output></p> <button onclick="startWorker()">Start Worker</button> <button onclick="stopWorker()">Stop Worker</button> <br><br> <script> var w; function startWorker() { if(typeof(Worker) !== "undefined") { if(typeof(w) == "undefined") { w = new Worker("demo_workers.js"); } w.onmessage = function(event) { document.getElementById("result").innerHTML = event.data; }; } else { document.getElementById("result").innerHTML = "Sorry! No Web Worker support."; } } function stopWorker() { w.terminate(); w = undefined; } </script> </body> </html>
10、Web Worker 和 DOM
由于 web worker 位于外部文件中,它们无法访问下例 JavaScript 对象:
- window 对象
- document 对象
- parent 对象
六、SSE
1、Server-Sent 事件 - One Way Messaging
Server-Sent 事件指的是网页自动从服务器获得更新。
以前也可能做到这一点,前提是网页不得不询问是否有可用的更新。通过 Server-Sent 事件,更新能够自动到达。
例如:Facebook/Twitter 更新、股价更新、新的博文、赛事结果,等等。
2、浏览器支持
表格中的数字指示完全支持 server-sent 事件的首个浏览器。
[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-ZjmoEPfd-1653830778577)(/image-20211123002615316.png)]
3、接收 Server-Sent 事件通知
EventSource 对象用于接收服务器发送事件通知:
1
2
3
4
5var source = new EventSource("demo_sse.php"); source.onmessage = function(event) { document.getElementById("result").innerHTML += event.data + "<br>"; };
例子解释:
- 创建一个新的 EventSource 对象,然后规定发送更新的页面的 URL(本例中是 “demo_sse.php”)
- 每当接收到一次更新,就会发生 onmessage 事件
- 当 onmessage 事件发生时,把已接收的数据推入 id 为 “result” 的元素中
4、检测 Server-Sent 事件支持
在 TIY 实例中,我们编写了一段额外的代码来检测服务器发送事件的浏览器支持:
1
2
3
4
5
6
7if(typeof(EventSource) !== "undefined") { // 是的!支持服务器发送事件! // 一些代码..... } else { // 抱歉!不支持服务器发送事件! }
5、服务器端代码实例
为了使上例运行,您需要能够发送数据更新的服务器(比如 PHP 或 ASP)。
服务器端事件流的语法非常简单。请把 “Content-Type” 报头设置为 “text/event-stream”。现在,您可以开始发送事件流了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16PHP 中的代码 (demo_sse.php): <?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: The server time is: {$time}nn"; flush(); ?> ASP 中的代码 (VB) (demo_sse.asp): <% Response.ContentType = "text/event-stream" Response.Expires = -1 Response.Write("data: The server time is: " & now()) Response.Flush() %>
代码解释:
- 把报头 “Content-Type” 设置为 “text/event-stream”
- 规定不对页面进行缓存
- 输出要发送的日期(始终以 "data: " 开头)
- 向网页刷新输出数据
6、EventSource 对象
在上例中,我们使用 onmessage 事件来获取消息。不过还可以使用其他事件:
事件 | 描述 |
---|---|
onopen | 当通往服务器的连接被打开 |
onmessage | 当接收到消息 |
onerror | 当发生错误 |
- parent 对象
六、SSE
1、Server-Sent 事件 - One Way Messaging
Server-Sent 事件指的是网页自动从服务器获得更新。
以前也可能做到这一点,前提是网页不得不询问是否有可用的更新。通过 Server-Sent 事件,更新能够自动到达。
例如:Facebook/Twitter 更新、股价更新、新的博文、赛事结果,等等。
2、浏览器支持
表格中的数字指示完全支持 server-sent 事件的首个浏览器。
[外链图片转存中…(img-ZjmoEPfd-1653830778577)]
3、接收 Server-Sent 事件通知
EventSource 对象用于接收服务器发送事件通知:
1
2
3
4
5var source = new EventSource("demo_sse.php"); source.onmessage = function(event) { document.getElementById("result").innerHTML += event.data + "<br>"; };
例子解释:
- 创建一个新的 EventSource 对象,然后规定发送更新的页面的 URL(本例中是 “demo_sse.php”)
- 每当接收到一次更新,就会发生 onmessage 事件
- 当 onmessage 事件发生时,把已接收的数据推入 id 为 “result” 的元素中
4、检测 Server-Sent 事件支持
在 TIY 实例中,我们编写了一段额外的代码来检测服务器发送事件的浏览器支持:
1
2
3
4
5
6
7if(typeof(EventSource) !== "undefined") { // 是的!支持服务器发送事件! // 一些代码..... } else { // 抱歉!不支持服务器发送事件! }
5、服务器端代码实例
为了使上例运行,您需要能够发送数据更新的服务器(比如 PHP 或 ASP)。
服务器端事件流的语法非常简单。请把 “Content-Type” 报头设置为 “text/event-stream”。现在,您可以开始发送事件流了。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16PHP 中的代码 (demo_sse.php): <?php header('Content-Type: text/event-stream'); header('Cache-Control: no-cache'); $time = date('r'); echo "data: The server time is: {$time}nn"; flush(); ?> ASP 中的代码 (VB) (demo_sse.asp): <% Response.ContentType = "text/event-stream" Response.Expires = -1 Response.Write("data: The server time is: " & now()) Response.Flush() %>
代码解释:
- 把报头 “Content-Type” 设置为 “text/event-stream”
- 规定不对页面进行缓存
- 输出要发送的日期(始终以 "data: " 开头)
- 向网页刷新输出数据
6、EventSource 对象
在上例中,我们使用 onmessage 事件来获取消息。不过还可以使用其他事件:
事件 | 描述 |
---|---|
onopen | 当通往服务器的连接被打开 |
onmessage | 当接收到消息 |
onerror | 当发生错误 |
最后
以上就是执着小蝴蝶最近收集整理的关于HTML5详解HTML5HTML5 API的全部内容,更多相关HTML5详解HTML5HTML5内容请搜索靠谱客的其他文章。
发表评论 取消回复