Html5 简明教程
HTML5 - Overview
HTML5 是 HTML 标准的下一个主要修订版,取代了 HTML 4.01、XHTML 1.0 和 XHTML 1.1。HTML5 是一种在万维网上构建和展示内容的标准。
HTML5 is the next major revision of the HTML standard superseding HTML 4.01, XHTML 1.0, and XHTML 1.1. HTML5 is a standard for structuring and presenting content on the World Wide Web.
HTML5 是万维网联盟 (W3C) 和网络超文本应用程序技术工作组 (WHATWG) 共同合作的成果。
HTML5 is a cooperation between the World Wide Web Consortium (W3C) and the Web Hypertext Application Technology Working Group (WHATWG).
新的标准融入了视频播放和拖放等功能,这些功能之前依赖于诸如 Adobe Flash、Microsoft Silverlight 和 Google Gears 等第三方浏览器插件。
The new standard incorporates features like video playback and drag-and-drop that have been previously dependent on third-party browser plug-ins such as Adobe Flash, Microsoft Silverlight, and Google Gears.
Browser Support
最新版本的 Apple Safari、Google Chrome、Mozilla Firefox 和 Opera 都支持很多 HTML5 功能,而 Internet Explorer 9.0 也会支持一些 HTML5 功能。
The latest versions of Apple Safari, Google Chrome, Mozilla Firefox, and Opera all support many HTML5 features and Internet Explorer 9.0 will also have support for some HTML5 functionality.
预装在 iPhone、iPad 和 Android 手机上的移动网络浏览器都对 HTML5 有着很好的支持。
The mobile web browsers that come pre-installed on iPhones, iPads, and Android phones all have excellent support for HTML5.
New Features
HTML5 引入了能在构建现代网站中帮助你的大量新元素和属性。下面是一组 HTML5 中引入的一些最突出的功能。
HTML5 introduces a number of new elements and attributes that can help you in building modern websites. Here is a set of some of the most prominent features introduced in HTML5.
-
New Semantic Elements − These are like <header>, <footer>, and <section>.
-
Forms 2.0 − Improvements to HTML web forms where new attributes have been introduced for <input> tag.
-
Persistent Local Storage − To achieve without resorting to third-party plugins.
-
WebSocket − A next-generation bidirectional communication technology for web applications.
-
Server-Sent Events − HTML5 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE).
-
Canvas − This supports a two-dimensional drawing surface that you can program with JavaScript.
-
Audio & Video − You can embed audio or video on your webpages without resorting to third-party plugins.
-
Geolocation − Now visitors can choose to share their physical location with your web application.
-
Microdata − This lets you create your own vocabularies beyond HTML5 and extend your web pages with custom semantics.
-
Drag and drop − Drag and drop the items from one location to another location on the same webpage.
Backward Compatibility
HTML5 尽可能设计为向后兼容现有网络浏览器。新功能建立在已有功能的基础上,允许您为较旧的浏览器提供备用内容。
HTML5 is designed, as much as possible, to be backward compatible with existing web browsers. Its new features have been built on existing features and allow you to provide fallback content for older browsers.
建议使用几行 JavaScript 来检测对各个 HTML5 功能的支持。
It is suggested to detect support for individual HTML5 features using a few lines of JavaScript.
如果您不熟悉任何以前版本的 HTML,我建议您在探索 HTML5 的功能之前先浏览我们的 HTML Tutorial 。
If you are not familiar with any previous version of HTML, I would recommend that you go through our HTML Tutorial before exploring the features of HTML5.
HTML5 - Syntax
HTML 5 语言具有“自定义”HTML 语法,该语法与发布在 Web 上的 HTML 4 和 XHTML1 文档兼容,但与 HTML 4 中更加深奥的 SGML 特性不兼容。
The HTML 5 language has a "custom" HTML syntax that is compatible with HTML 4 and XHTML1 documents published on the Web, but is not compatible with the more esoteric SGML features of HTML 4.
HTML 5 的语法规则与 XHTML 不同,在 XHTML 中,我们需要小写标签名称、引用属性、属性必须具有值并关闭所有空元素。
HTML 5 does not have the same syntax rules as XHTML where we needed lower case tag names, quoting our attributes, an attribute had to have a value and to close all empty elements.
HTML5 具有很大的灵活性,它支持以下特性 −
HTML5 comes with a lot of flexibility and it supports the following features −
-
Uppercase tag names.
-
Quotes are optional for attributes.
-
Attribute values are optional.
-
Closing empty elements are optional.
The DOCTYPE
较早版本的 HTML 中的 DOCTYPE 更长,因为 HTML 语言基于 SGML,因此需要引用 DTD。
DOCTYPEs in older versions of HTML were longer because the HTML language was SGML based and therefore required a reference to a DTD.
HTML 5 作者会使用简单的语法指定 DOCTYPE,如下所示 −
HTML 5 authors would use simple syntax to specify DOCTYPE as follows −
<!DOCTYPE html>
上面的语法不分大小写。
The above syntax is case-insensitive.
Character Encoding
HTML 5 作者可以使用简单的语法指定如下字符编码:
HTML 5 authors can use simple syntax to specify Character Encoding as follows −
<meta charset = "UTF-8">
上面的语法不分大小写。
The above syntax is case-insensitive.
The <script> tag
添加一个值是 "text/javascript" 的类型属性到脚本元素是常见的做法,如下所示:
It’s common practice to add a type attribute with a value of "text/javascript" to script elements as follows −
<script type = "text/javascript" src = "scriptfile.js"></script>
HTML 5 删除了需要的额外信息,你可以简单地使用以下语法:
HTML 5 removes extra information required and you can use simply following syntax −
<script src = "scriptfile.js"></script>
The <link> tag
到目前为止,你的编写 <link> 如下:
So far you were writing <link> as follows −
<link rel = "stylesheet" type = "text/css" href = "stylefile.css">
HTML 5 删除了需要的额外信息,你可以简单地使用以下语法:
HTML 5 removes extra information required and you can simply use the following syntax −
<link rel = "stylesheet" href = "stylefile.css">
HTML5 Elements
HTML5 元素使用开始标签和结束标签标记。标签使用包含标签名称的尖角符号定界。
HTML5 elements are marked up using start tags and end tags. Tags are delimited using angle brackets with the tag name in between.
开始标签和结束标签的区别是后者在标签名称前包含一个斜杠。
The difference between start tags and end tags is that the latter includes a slash before the tag name.
下面是 HTML5 元素的示例:
Following is the example of an HTML5 element −
<p>...</p>
HTML5 标签名称不区分大小写,可以使用全部大写字母或混合字母,尽管最常见的惯例是坚持使用小写字母。
HTML5 tag names are case insensitive and may be written in all uppercase or mixed case, although the most common convention is to stick with lowercase.
大多数元素包含一些内容,如 <p>…</p> 的内容时段落。不过,有些元素禁止包含任何内容,它们被称为空元素。例如 br, hr, link, meta 等。
Most of the elements contain some content like <p>…</p> contains a paragraph. Some elements, however, are forbidden from containing any content at all and these are known as void elements. For example, br, hr, link, meta, etc.
下面是 HTML5 Elements 的完整列表。
Here is a complete list of HTML5 Elements.
HTML5 Attributes
这些元素可包含用于设置元素各种属性的属性。
Elements may contain attributes that are used to set various properties of an element.
有些属性在全局中定义,可在任何元素中使用,而有些属性仅针对特定的元素定义。所有属性均有一个名称和一个值,如下面的示例所示。
Some attributes are defined globally and can be used on any element, while others are defined for specific elements only. All attributes have a name and a value and look like as shown below in the example.
下面是 HTML5 属性的示例,它展示了如何将一个 div 元素标记为带有"example"的值的 class 属性 −
Following is the example of an HTML5 attribute which illustrates how to mark up a div element with an attribute named class using a value of "example" −
<div class = "example">...</div>
属性只能在起始标签内指定,绝对不可在结束标签内使用。
Attributes may only be specified within start tags and must never be used in end tags.
HTML5 属性不区分大小写,可以全部采用大写或混合大小写编写,但最常见的惯例是坚持使用小写。
HTML5 attributes are case insensitive and may be written in all uppercase or mixed case, although the most common convention is to stick with lowercase.
下面是 HTML5 Attributes 的完整列表。
Here is a complete list of HTML5 Attributes.
HTML5 Document
为了更好的结构,引入了以下标签 −
The following tags have been introduced for better structure −
-
section − This tag represents a generic document or application section. It can be used together with h1-h6 to indicate the document structure.
-
article − This tag represents an independent piece of content of a document, such as a blog entry or newspaper article.
-
aside − This tag represents a piece of content that is only slightly related to the rest of the page.
-
header − This tag represents the header of a section.
-
footer − This tag represents a footer for a section and can contain information about the author, copyright information, et cetera.
-
nav − This tag represents a section of the document intended for navigation.
-
dialog − This tag can be used to mark up a conversation.
-
figure − This tag can be used to associate a caption together with some embedded content, such as a graphic or video.
HTML 5 文档的标记类似如下 −
The markup for an HTML 5 document would look like the following −
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>...</title>
</head>
<body>
<header>...</header>
<nav>...</nav>
<article>
<section>
...
</section>
</article>
<aside>...</aside>
<footer>...</footer>
</body>
</html>
<!DOCTYPE html>
<html>
<head>
<meta charset = "utf-8">
<title>...</title>
</head>
<body>
<header role = "banner">
<h1>HTML5 Document Structure Example</h1>
<p>This page should be tried in safari, chrome or Mozila.</p>
</header>
<nav>
<ul>
<li><a href = "https://www.tutorialspoint.com/html">HTML Tutorial</a></li>
<li><a href = "https://www.tutorialspoint.com/css">CSS Tutorial</a></li>
<li><a href = "https://www.tutorialspoint.com/javascript">
JavaScript Tutorial</a></li>
</ul>
</nav>
<article>
<section>
<p>Once article can have multiple sections</p>
</section>
</article>
<aside>
<p>This is aside part of the web page</p>
</aside>
<footer>
<p>Created by <a href = "https://tutorialspoint.com/">Tutorials Point</a></p>
</footer>
</body>
</html>
它将产生以下结果 −
It will produce the following result −
HTML5 - Attributes
正如前一章所解释的,元素可能包含属性,用于设置元素的各种属性。
As explained in the previous chapter, elements may contain attributes that are used to set various properties of an element.
有些属性在全局中定义,可在任何元素中使用,而有些属性仅针对特定的元素定义。所有属性均有一个名称和一个值,如下面的示例所示。
Some attributes are defined globally and can be used on any element, while others are defined for specific elements only. All attributes have a name and a value and look like as shown below in the example.
以下是如何使用“示例”的值标记带有名为 class 的属性的 div 元素的 HTML5 属性示例:
Following is the example of an HTML5 attributes which illustrates how to mark up a div element with an attribute named class using a value of "example" −
<div class = "example">...</div>
属性只能在 start tags 中指定,并且绝不能在 end tags 中使用。
Attributes may only be specified within start tags and must never be used in end tags.
HTML5 属性不区分大小写,可以全部采用大写或混合大小写编写,但最常见的惯例是坚持使用小写。
HTML5 attributes are case insensitive and may be written in all uppercase or mixed case, although the most common convention is to stick with lowercase.
Standard Attributes
以下列出的属性受几乎所有 HTML 5 标记支持。
The attributes listed below are supported by almost all the HTML 5 tags.
Attribute |
Options |
Function |
accesskey |
User Defined |
Specifies a keyboard shortcut to access an element. |
align |
right, left, center |
Horizontally aligns tags |
background |
URL |
Places an background image behind an element |
bgcolor |
numeric, hexidecimal, RGB values |
Places a background color behind an element |
class |
User Defined |
Classifies an element for use with Cascading Style Sheets. |
contenteditable |
true, false |
Specifies if the user can edit the element’s content or not. |
contextmenu |
Menu id |
Specifies the context menu for an element. |
data-XXXX |
User Defined |
Custom attributes. Authors of a HTML document can define their own attributes. Must start with "data-". |
draggable |
true,false, auto |
Specifies whether or not a user is allowed to drag an element. |
height |
Numeric Value |
Specifies the height of tables, images, or table cells. |
hidden |
hidden |
Specifies whether element should be visible or not. |
id |
User Defined |
Names an element for use with Cascading Style Sheets. |
item |
List of elements |
Used to group elements. |
itemprop |
List of items |
Used to group items. |
spellcheck |
true, false |
Specifies if the element must have it’s spelling or grammar checked. |
style |
CSS Style sheet |
Specifies an inline style for an element. |
subject |
User define id |
Specifies the element’s corresponding item. |
tabindex |
Tab number |
Specifies the tab order of an element. |
title |
User Defined |
"Pop-up" title for your elements. |
valign |
top, middle, bottom |
Vertically aligns tags within an HTML element. |
width |
Numeric Value |
Specifies the width of tables, images, or table cells. |
有关 HTML5 标记和相关属性的完整列表,请查看我们对 HTML5 Tags 的引用。
For a complete list of HTML5 Tags and related attributes, please check our reference to HTML5 Tags.
Custom Attributes
HTML 5 中引入的一项新功能是添加了自定义数据属性。
A new feature being introduced in HTML 5 is the addition of custom data attributes.
自定义数据属性以 data- 开头,并会根据您的要求进行命名。以下是简单的示例 −
A custom data attribute starts with data- and would be named based on your requirement. Here is a simple example −
<div class = "example" data-subject = "physics" data-level = "complex">
...
</div>
上面的代码将与两个称为 datasubject 和 data-level 的自定义属性形成完全有效的 HTML5。您将能够使用 JavaScript API 或 CSS 获取这些属性的值,就像获取标准属性的值一样。
The above code will be perfectly valid HTML5 with two custom attributes called datasubject and data-level. You would be able to get the values of these attributes using JavaScript APIs or CSS in similar way as you get for standard attributes.
HTML5 - Events
当用户访问您的网站时,他们会执行各种活动,例如单击文本、图像和链接,将鼠标悬停在定义的元素上,等等。这些都是 JavaScript 所说的 events 的示例。
When users visit your website, they perform various activities such as clicking on text and images and links, hover over defined elements, etc. These are examples of what JavaScript calls events.
我们可以在 Javascript 或 VBscript 中编写我们的事件处理程序,并且您可以将这些事件处理程序指定为事件标记属性的值。HTML5 规范定义了如下所列的各种事件属性 −
We can write our event handlers in Javascript or VBscript and you can specify these event handlers as a value of event tag attribute. The HTML5 specification defines various event attributes as listed below −
当对任何 HTML5 元素发生任何事件时,我们可以使用以下属性来触发任何作为值给出的 javascript 或 vbscript 代码。
We can use the following set of attributes to trigger any javascript or vbscript code given as value, when there is any event that takes place for any HTML5 element.
我们会在后续章节详细讨论这些元素时涵盖特定于元素的事件。
We would cover element-specific events while discussing those elements in detail in subsequent chapters.
Attribute |
Value |
Description |
offline |
script |
Triggers when the document goes offline |
onabort |
script |
Triggers on an abort event |
onafterprint |
script |
Triggers after the document is printed |
onbeforeonload |
script |
Triggers before the document loads |
onbeforeprint |
script |
Triggers before the document is printed |
onblur |
script |
Triggers when the window loses focus |
oncanplay |
script |
Triggers when media can start play, but might has to stop for buffering |
oncanplaythrough |
script |
Triggers when media can be played to the end, without stopping for buffering |
onchange |
script |
Triggers when an element changes |
onclick |
script |
Triggers on a mouse click |
oncontextmenu |
script |
Triggers when a context menu is triggered |
ondblclick |
script |
Triggers on a mouse double-click |
ondrag |
script |
Triggers when an element is dragged |
ondragend |
script |
Triggers at the end of a drag operation |
ondragenter |
script |
Triggers when an element has been dragged to a valid drop target |
ondragleave |
script |
Triggers when an element leaves a valid drop target |
ondragover |
script |
Triggers when an element is being dragged over a valid drop target |
ondragstart |
script |
Triggers at the start of a drag operation |
ondrop |
script |
Triggers when dragged element is being dropped |
ondurationchange |
script |
Triggers when the length of the media is changed |
onemptied |
script |
Triggers when a media resource element suddenly becomes empty. |
onended |
script |
Triggers when media has reach the end |
onerror |
script |
Triggers when an error occur |
onfocus |
script |
Triggers when the window gets focus |
onformchange |
script |
Triggers when a form changes |
onforminput |
script |
Triggers when a form gets user input |
onhaschange |
script |
Triggers when the document has change |
oninput |
script |
Triggers when an element gets user input |
oninvalid |
script |
Triggers when an element is invalid |
onkeydown |
script |
Triggers when a key is pressed |
onkeypress |
script |
Triggers when a key is pressed and released |
onkeyup |
script |
Triggers when a key is released |
onload |
script |
Triggers when the document loads |
onloadeddata |
script |
Triggers when media data is loaded |
onloadedmetadata |
script |
Triggers when the duration and other media data of a media element is loaded |
onloadstart |
script |
Triggers when the browser starts to load the media data |
onmessage |
script |
Triggers when the message is triggered |
onmousedown |
script |
Triggers when a mouse button is pressed |
onmousemove |
script |
Triggers when the mouse pointer moves |
onmouseout |
script |
Triggers when the mouse pointer moves out of an element |
onmouseover |
script |
Triggers when the mouse pointer moves over an element |
onmouseup |
script |
Triggers when a mouse button is released |
onmousewheel |
script |
Triggers when the mouse wheel is being rotated |
onoffline |
script |
Triggers when the document goes offline |
onoine |
script |
Triggers when the document comes online |
ononline |
script |
Triggers when the document comes online |
onpagehide |
script |
Triggers when the window is hidden |
onpageshow |
script |
Triggers when the window becomes visible |
onpause |
script |
Triggers when media data is paused |
onplay |
script |
Triggers when media data is going to start playing |
onplaying |
script |
Triggers when media data has start playing |
onpopstate |
script |
Triggers when the window’s history changes |
onprogress |
script |
Triggers when the browser is fetching the media data |
onratechange |
script |
Triggers when the media data’s playing rate has changed |
onreadystatechange |
script |
Triggers when the ready-state changes |
onredo |
script |
Triggers when the document performs a redo |
onresize |
script |
Triggers when the window is resized |
onscroll |
script |
Triggers when an element’s scrollbar is being scrolled |
onseeked |
script |
Triggers when a media element’s seeking attribute is no longer true, and the seeking has ended |
onseeking |
script |
Triggers when a media element’s seeking attribute is true, and the seeking has begun |
onselect |
script |
Triggers when an element is selected |
onstalled |
script |
Triggers when there is an error in fetching media data |
onstorage |
script |
Triggers when a document loads |
onsubmit |
script |
Triggers when a form is submitted |
onsuspend |
script |
Triggers when the browser has been fetching media data, but stopped before the entire media file was fetched |
ontimeupdate |
script |
Triggers when media changes its playing position |
onundo |
script |
Triggers when a document performs an undo |
onunload |
script |
Triggers when the user leaves the document |
onvolumechange |
script |
Triggers when media changes the volume, also when volume is set to "mute" |
onwaiting |
script |
Triggers when media has stopped playing, but is expected to resume |
HTML5 - Web Forms 2.0
Web 表单 2.0 是在 HTML4 中找到的表单功能的扩展。HTML5 中的表单元素和属性提供了比 HTML4 更高级别的语义标记,并且使我们摆脱了 HTML4 中所需的繁琐的脚本和样式。
Web Forms 2.0 is an extension to the forms features found in HTML4. Form elements and attributes in HTML5 provide a greater degree of semantic mark-up than HTML4 and free us from a great deal of tedious scripting and styling that was required in HTML4.
The <input> element in HTML4
HTML4 输入元素使用 type 属性来指定数据类型。HTML4 提供了以下类型 −
HTML4 input elements use the type attribute to specify the data type.HTML4 provides following types −
Sr.No. |
Type & Description |
1 |
text A free-form text field, nominally free of line breaks. |
2 |
password A free-form text field for sensitive information, nominally free of line breaks. |
3 |
checkbox A set of zero or more values from a predefined list. |
4 |
radio An enumerated value. |
5 |
submit A free form of button initiates form submission. |
6 |
file An arbitrary file with a MIME type and optionally a file name. |
7 |
image A coordinate, relative to a particular image’s size, with the extra semantic that it must be the last value selected and initiates form submission. |
8 |
hidden An arbitrary string that is not normally displayed to the user. |
9 |
select An enumerated value, much like the radio type. |
10 |
textarea A free-form text field, nominally with no line break restrictions. |
11 |
button A free form of button which can initiates any event related to button. |
以下是一个使用标签、单选按钮和提交按钮的简单示例 −
Following is the simple example of using labels, radio buttons, and submit buttons −
...
<form action = "http://example.com/cgiscript.pl" method = "post">
<p>
<label for = "firstname">first name: </label>
<input type = "text" id = "firstname"><br />
<label for = "lastname">last name: </label>
<input type = "text" id = "lastname"><br />
<label for = "email">email: </label>
<input type = "text" id = "email"><br>
<input type = "radio" name = "sex" value = "male"> Male<br>
<input type = "radio" name = "sex" value = "female"> Female<br>
<input type = "submit" value = "send"> <input type = "reset">
</p>
</form>
...
The <input> element in HTML5
除了上述属性之外,HTML5 输入元素还为 type 属性引入了几个新值。这些如下所示。
Apart from the above-mentioned attributes, HTML5 input elements introduced several new values for the type attribute. These are listed below.
NOTE − 使用最新版本的 Opera 浏览器尝试所有以下示例。
NOTE − Try all the following example using latest version of Opera browser.
Sr.No. |
Type & Description |
1 |
datetimeA date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601 with the time zone set to UTC. |
2 |
datetime-localA date and time (year, month, day, hour, minute, second, fractions of a second) encoded according to ISO 8601, with no time zone information. |
3 |
dateA date (year, month, day) encoded according to ISO 8601. |
4 |
month A date consisting of a year and a month encoded according to ISO 8601. |
5 |
weekA date consisting of a year and a week number encoded according to ISO 8601. |
6 |
timeA time (hour, minute, seconds, fractional seconds) encoded according to ISO 8601. |
7 |
numberIt accepts only numerical value. The step attribute specifies the precision, defaulting to 1. |
8 |
rangeThe range type is used for input fields that should contain a value from a range of numbers. |
9 |
emailIt accepts only email value. This type is used for input fields that should contain an e-mail address. If you try to submit a simple text, it forces to enter only email address in email@example.com format. |
10 |
urlIt accepts only URL value. This type is used for input fields that should contain a URL address. If you try to submit a simple text, it forces to enter only URL address either in [role="bare"]http://www.example.com format or in [role="bare"]http://example.com format. |
The <output> element
HTML5 引入了新元素 <output>,该元素用于表示不同类型输出的结果,例如由脚本编写的输出。
HTML5 introduced a new element <output> which is used to represent the result of different types of output, such as output written by a script.
您可以使用 for 属性来指定输出元素与文档中影响计算的其他元素(例如,作为输入或参数)之间的关系。for 属性的值是其他元素的 ID 的空格分隔列表。
You can use the for attribute to specify a relationship between the output element and other elements in the document that affected the calculation (for example, as inputs or parameters). The value of the for attribute is a space-separated list of IDs of other elements.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function showResult() {
x = document.forms["myform"]["newinput"].value;
document.forms["myform"]["result"].value = x;
}
</script>
</head>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get" name = "myform">
Enter a value : <input type = "text" name = "newinput" />
<input type = "button" value = "Result" onclick = "showResult();" />
<output name = "result"></output>
</form>
</body>
</html>
它将产生以下结果 −
It will produce the following result −
The placeholder attribute
HTML5 引入了一个名为 placeholder 的新属性。在 <input> 和 <textarea> 元素上,此属性为用户提供提示,说明该字段中可以输入什么内容。占位符文本不得包含回车或换行符。
HTML5 introduced a new attribute called placeholder. This attribute on <input> and <textarea> elements provide a hint to the user of what can be entered in the field. The placeholder text must not contain carriage returns or line-feeds.
占位符属性的简单语法如下所示:
Here is the simple syntax for placeholder attribute −
<input type = "text" name = "search" placeholder = "search the web"/>
只有最新版本的 Mozilla、Safari 和 Crome 浏览器支持此属性。
This attribute is supported by latest versions of Mozilla, Safari and Crome browsers only.
<!DOCTYPE HTML>
<html>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get">
Enter email : <input type = "email" name = "newinput"
placeholder = "email@example.com"/>
<input type = "submit" value = "submit" />
</form>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
The autofocus attribute
这是一个简单的单步模式,在文档加载时很容易用 JavaScript 编写,自动聚焦一个特定的表单字段。
This is a simple one-step pattern, easily programmed in JavaScript at the time of document load, automatically focus one particular form field.
HTML5 引入了一个名为 autofocus 的新属性,它将用于以下内容:
HTML5 introduced a new attribute called autofocus which would be used as follows −
<input type = "text" name = "search" autofocus/>
只有最新版本的 Mozilla、Safari 和 Chrome 浏览器支持此属性。
This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers only.
<!DOCTYPE HTML>
<html>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get">
Enter email : <input type = "text" name = "newinput" autofocus/>
<p>Try to submit using Submit button</p>
<input type = "submit" value = "submit" />
</form>
</body>
</html>
The required attribute
现在,你不必使用 JavaScript 进行客户端验证,例如永远不会提交空文本框,因为 HTML5 引入了一个名为 required 的新属性,它将用于以下内容并坚持要求提供一个值:
Now you do not need to have JavaScript for client-side validations like empty text box would never be submitted because HTML5 introduced a new attribute called required which would be used as follows and would insist to have a value −
<input type = "text" name = "search" required/>
只有最新版本的 Mozilla、Safari 和 Chrome 浏览器支持此属性。
This attribute is supported by latest versions of Mozilla, Safari and Chrome browsers only.
<!DOCTYPE HTML>
<html>
<body>
<form action = "/cgi-bin/html5.cgi" method = "get">
Enter email : <input type = "text" name = "newinput" required/>
<p>Try to submit using Submit button</p>
<input type = "submit" value = "submit" />
</form>
</body>
</html>
它将产生以下结果 −
It will produce the following result −
HTML5 - SVG
SVG 代表 *S*calable *V*ector *G*raphics,它是用于在 XML 中描述 2D 图形和图形应用程序的语言,然后由 SVG 浏览器渲染 XML。
SVG stands for *S*calable *V*ector *G*raphics and it is a language for describing 2D-graphics and graphical applications in XML and the XML is then rendered by an SVG viewer.
SVG 主要适用于矢量类型图表,如饼图、X、Y 坐标系中的二维图表等。
SVG is mostly useful for vector type diagrams like Pie charts, Two-dimensional graphs in an X,Y coordinate system etc.
SVG 于 2003 年 1 月 14 日成为 W3C 推荐书,你可以在 SVG Specification 上查看 SVG 规范的最新版本。
SVG became a W3C Recommendation 14. January 2003 and you can check latest version of SVG specification at SVG Specification.
Viewing SVG Files
大多数的网络浏览器可以展示 SVG,就像它们可以展示 PNG、GIF 和 JPG 一样。Internet Explorer 用户可能得安装 Adobe SVG Viewer,这样才能在浏览器中查看 SVG。
Most of the web browsers can display SVG just like they can display PNG, GIF, and JPG. Internet Explorer users may have to install the Adobe SVG Viewer to be able to view SVG in the browser.
Embedding SVG in HTML5
HTML5 允许直接使用 <svg>…</svg> 标记来嵌入 SVG,该标记具有以下简单的语法 −
HTML5 allows embedding SVG directly using <svg>…</svg> tag which has following simple syntax −
<svg xmlns = "http://www.w3.org/2000/svg">
...
</svg>
Firefox 3.7 还引入了一个配置选项("about:config"),你可以用以下步骤启用 HTML5 −
Firefox 3.7 has also introduced a configuration option ("about:config") where you can enable HTML5 using the following steps −
-
Type about:config in your Firefox address bar.
-
Click the "I’ll be careful, I promise!" button on the warning message that appears (and make sure you adhere to it!).
-
Type html5.enable into the filter bar at the top of the page.
-
Currently it would be disabled, so click it to toggle the value to true.
现在,你的 Firefox HTML5 解析器应该被启用了,你应该能够试验以下示例。
Now your Firefox HTML5 parser should be enabled and you should be able to experiment with the following examples.
HTML5 − SVG Circle
以下是对 SVG 示例的 HTML5 版本,它将使用 <circle> 标记绘制一个圆 −
Following is the HTML5 version of an SVG example which would draw a circle using <circle> tag −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-20%);
-ms-transform: translateX(-20%);
transform: translateX(-20%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Circle</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<circle id = "redcircle" cx = "50" cy = "50" r = "50" fill = "red" />
</svg>
</body>
</html>
这会在启用了 HTML5 的最新版本 Firefox 中产生以下结果。
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 − SVG Rectangle
以下是使用 <rect> 标记绘制一个矩形的 SVG 示例的 HTML5 版本 −
Following is the HTML5 version of an SVG example which would draw a rectangle using <rect> tag −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Rectangle</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<rect id = "redrect" width = "300" height = "100" fill = "red" />
</svg>
</body>
</html>
这会在启用了 HTML5 的最新版本 Firefox 中产生以下结果。
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 − SVG Line
以下是使用 <line> 标记绘制一条线的 SVG 示例的 HTML5 版本 −
Following is the HTML5 version of an SVG example which would draw a line using <line> tag −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Line</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<line x1 = "0" y1 = "0" x2 = "200" y2 = "100"
style = "stroke:red;stroke-width:2"/>
</svg>
</body>
</html>
你可以使用 style 属性,它允许你设置其他样式信息,例如颜色、描边宽度等。
You can use the style attribute which allows you to set additional style information like stroke and fill colors, width of the stroke, etc.
这会在启用了 HTML5 的最新版本 Firefox 中产生以下结果。
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 − SVG Ellipse
下面是对 SVG 示例的 HTML5 版本,它将使用 <ellipse> 标记绘制一个椭圆 −
Following is the HTML5 version of an SVG example which would draw an ellipse using <ellipse> tag −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-40%);
-ms-transform: translateX(-40%);
transform: translateX(-40%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Ellipse</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<ellipse cx = "100" cy = "50" rx = "100" ry = "50" fill = "red" />
</svg>
</body>
</html>
这会在启用了 HTML5 的最新版本 Firefox 中产生以下结果。
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 − SVG Polygon
以下是使用 <polygon> 标记绘制一个多边形的 SVG 示例的 HTML5 版本 −
Following is the HTML5 version of an SVG example which would draw a polygon using <polygon> tag −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-50%);
-ms-transform: translateX(-50%);
transform: translateX(-50%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Polygon</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<polygon points = "20,10 300,20, 170,50" fill = "red" />
</svg>
</body>
</html>
这会在启用了 HTML5 的最新版本 Firefox 中产生以下结果。
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 − SVG Polyline
以下是使用 <polyline> 标记绘制一个折线的 SVG 示例的 HTML5 版本 −
Following is the HTML5 version of an SVG example which would draw a polyline using <polyline> tag −
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-20%);
-ms-transform: translateX(-20%);
transform: translateX(-20%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Polyline</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<polyline points = "0,0 0,20 20,20 20,40 40,40 40,60" fill = "red" />
</svg>
</body>
</html>
这会在启用了 HTML5 的最新版本 Firefox 中产生以下结果。
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 − SVG Gradients
以下是使用 <ellipse> 标记并且使用 <radialGradient> 标记定义 SVG 径向渐变绘制一个椭圆的 SVG 示例的 HTML5 版本。
Following is the HTML5 version of an SVG example which would draw an ellipse using <ellipse> tag and would use <radialGradient> tag to define an SVG radial gradient.
同样,你可以使用 <linearGradient> 标记创建 SVG 线性渐变。
Similarly, you can use <linearGradient> tag to create SVG linear gradient.
<!DOCTYPE html>
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-40%);
-ms-transform: translateX(-40%);
transform: translateX(-40%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Gradient Ellipse</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<defs>
<radialGradient id="gradient" cx = "50%" cy = "50%" r = "50%" fx = "50%"
fy = "50%">
<stop offset = "0%" style = "stop-color:rgb(200,200,200); stop-opacity:0"/>
<stop offset = "100%" style = "stop-color:rgb(0,0,255); stop-opacity:1"/>
</radialGradient>
</defs>
<ellipse cx = "100" cy = "50" rx = "100" ry = "50"
style = "fill:url(#gradient)" />
</svg>
</body>
</html>
这会在启用了 HTML5 的最新版本 Firefox 中产生以下结果。
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 − SVG Star
以下是使用 <polygon> 标记绘制一颗星的 SVG 示例的 HTML5 版本。
Following is the HTML5 version of an SVG example which would draw a star using <polygon> tag.
<html>
<head>
<style>
#svgelem {
position: relative;
left: 50%;
-webkit-transform: translateX(-40%);
-ms-transform: translateX(-40%);
transform: translateX(-40%);
}
</style>
<title>SVG</title>
<meta charset = "utf-8" />
</head>
<body>
<h2 align = "center">HTML5 SVG Star</h2>
<svg id = "svgelem" height = "200" xmlns = "http://www.w3.org/2000/svg">
<polygon points = "100,10 40,180 190,60 10,60 160,180" fill = "red"/>
</svg>
</body>
</html>
这会在启用了 HTML5 的最新版本 Firefox 中产生以下结果。
This would produce the following result in HTML5 enabled latest version of Firefox.
HTML5 - MathML
HTML5 的 HTML 语法允许使用 <math>…</math> 标记在文档中使用 MathML 元素。
The HTML syntax of HTML5 allows for MathML elements to be used inside a document using <math>…</math> tags.
大部分网络浏览器都能显示 MathML 标签。如果你的浏览器不支持 MathML,那么我建议你使用最新版本的 Firefox。
Most of the web browsers can display MathML tags. If your browser does not support MathML, then I would suggest you to use latest version of Firefox.
MathML Examples
以下是包含 MathML 的有效的 HTML5 文档:
Following is a valid HTML5 document with MathML −
<!doctype html>
<html>
<head>
<meta charset = "UTF-8">
<title>Pythagorean theorem</title>
</head>
<body>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<msup><mi>a</mi><mn>2</mn></msup>
<mo>+</mo>
<msup><mi>b</mi><mn>2</mn></msup>
<mo> = </mo>
<msup><mi>c</mi><mn>2</mn></msup>
</mrow>
</math>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
Using MathML Characters
考虑以下使用 字符的标记:
Consider, following is the markup which makes use of the characters ⁢ −
<!doctype html>
<html>
<head>
<meta charset = "UTF-8">
<title>MathML Examples</title>
</head>
<body>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mrow>
<msup>
<mi>x</mi>
<mn>2</mn>
</msup>
<mo>+</mo>
<mrow>
<mn>4</mn>
<mo></mo>
<mi>x</mi>
</mrow>
<mo>+</mo>
<mn>4</mn>
</mrow>
<mo>=</mo>
<mn>0</mn>
</mrow>
</math>
</body>
</html>
这将产生以下结果。如果你看不到正确的结果,比如 x2 + 4x + 4 = 0,那么使用 Firefox 3.5 或更高版本。
This would produce the following result. If you are not able to see proper result like x2 + 4x + 4 = 0, then use Firefox 3.5 or higher version.
这会产生以下结果 −
This will produce the following result −
Matrix Presentation Examples
考虑以下这个用于表示一个简单的 2x2 矩阵的示例:
Consider the following example which would be used to represent a simple 2x2 matrix −
<!doctype html>
<html>
<head>
<meta charset = "UTF-8">
<title>MathML Examples</title>
</head>
<body>
<math xmlns = "http://www.w3.org/1998/Math/MathML">
<mrow>
<mi>A</mi>
<mo>=</mo>
<mfenced open = "[" close="]">
<mtable>
<mtr>
<mtd><mi>x</mi></mtd>
<mtd><mi>y</mi></mtd>
</mtr>
<mtr>
<mtd><mi>z</mi></mtd>
<mtd><mi>w</mi></mtd>
</mtr>
</mtable>
</mfenced>
</mrow>
</math>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
这将产生以下结果。如果你看不到正确的结果,那么使用 Firefox 3.5 或更高版本。
This would produce the following result. If you are not able to see proper result, then use Firefox 3.5 or higher version.
HTML5 - Web Storage
HTML5 引入了两种与 HTTP 会话 cookie 相似的机制,用于在客户端存储结构化数据并克服以下缺点。
HTML5 introduces two mechanisms, similar to HTTP session cookies, for storing structured data on the client side and to overcome following drawbacks.
-
Cookies are included with every HTTP request, thereby slowing down your web application by transmitting the same data.
-
Cookies are included with every HTTP request, thereby sending data unencrypted over the internet.
-
Cookies are limited to about 4 KB of data. Not enough to store required data.
这两个存储是 session storage 和 local storage ,它们将用于处理不同的情况。
The two storages are session storage and local storage and they would be used to handle different situations.
几乎所有浏览器的最新版本都支持 HTML5 存储,包括 Internet Explorer。
The latest versions of pretty much every browser supports HTML5 Storage including Internet Explorer.
Session Storage
会话存储是为以下场景设计的:用户执行单一交易,但可以在同一时间在不同窗口中执行多笔交易。
The Session Storage is designed for scenarios where the user is carrying out a single transaction, but could be carrying out multiple transactions in different windows at the same time.
Example
例如,如果一个用户在两个不同的窗口中使用同一网站购买机票。如果该网站使用 cookie 来跟踪用户正在购买哪张机票,那么当用户在两个窗口中的页面间点击时,当前购买的机票将从一个窗口“泄漏”到另一个窗口,从而可能导致用户不知不觉地购买两张同一航班的机票。
For example, if a user buying plane tickets in two different windows, using the same site. If the site used cookies to keep track of which ticket the user was buying, then as the user clicked from page to page in both windows, the ticket currently being purchased would "leak" from one window to the other, potentially causing the user to buy two tickets for the same flight without really noticing.
HTML5 引入了 sessionStorage 属性,网站将使用该属性向会话存储添加数据,并且同一网站在该窗口中打开的任何页面都可以访问该数据,即 session ,一旦你关闭窗口,会话就会丢失。
HTML5 introduces the sessionStorage attribute which would be used by the sites to add data to the session storage, and it will be accessible to any page from the same site opened in that window, i.e., session and as soon as you close the window, the session would be lost.
以下代码将设置会话变量并访问该变量:
Following is the code which would set a session variable and access that variable −
<!DOCTYPE HTML>
<html>
<body>
<script type = "text/javascript">
if( sessionStorage.hits ) {
sessionStorage.hits = Number(sessionStorage.hits) +1;
} else {
sessionStorage.hits = 1;
}
document.write("Total Hits :" + sessionStorage.hits );
</script>
<p>Refresh the page to increase number of hits.</p>
<p>Close the window and open it again and check the result.</p>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
Local Storage
本地存储用于跨多个窗口且持续整个会话的存储。特别是,出于性能原因,网络应用程序可能希望在客户端存储兆字节的用户数据,例如用户编写的完整文档或用户的邮箱。
The Local Storage is designed for storage that spans multiple windows, and lasts beyond the current session. In particular, Web applications may wish to store megabytes of user data, such as entire user-authored documents or a user’s mailbox, on the client side for performance reasons.
同样,Cookie 不能很好地处理这种情况,因为它们会随每个请求一起传输。
Again, cookies do not handle this case well, because they are transmitted with every request.
Example
HTML5 引入了 localStorage 属性,该属性用于访问页面的本地存储区域,且没有时间限制,并且无论何时你使用该页面,此本地存储都可用。
HTML5 introduces the localStorage attribute which would be used to access a page’s local storage area without no time limit and this local storage will be available whenever you would use that page.
以下代码将设置一个本地存储变量,并且每次访问此页面(甚至下一次当你打开窗口时)都会访问该变量:
Following is the code which would set a local storage variable and access that variable every time this page is accessed, even next time, when you open the window −
<!DOCTYPE HTML>
<html>
<body>
<script type = "text/javascript">
if( localStorage.hits ) {
localStorage.hits = Number(localStorage.hits) +1;
} else {
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
<p>Refresh the page to increase number of hits.</p>
<p>Close the window and open it again and check the result.</p>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
Delete Web Storage
在本地机器上存储敏感数据可能是危险的,并且可能留下安全漏洞。
Storing sensitive data on local machine could be dangerous and could leave a security hole.
会话存储数据将在会话终止后立即被浏览器删除。
The Session Storage Data would be deleted by the browsers immediately after the session gets terminated.
要清除本地存储设置,你需要调用 localStorage.remove('key') ;其中“key”是要删除的值的键。如果你想清除所有设置,则需要调用 localStorage.clear() 方法。
To clear a local storage setting you would need to call localStorage.remove('key'); where 'key' is the key of the value you want to remove. If you want to clear all settings, you need to call localStorage.clear() method.
以下是清除完整本地存储的代码:
Following is the code which would clear complete local storage −
<!DOCTYPE HTML>
<html>
<body>
<script type = "text/javascript">
localStorage.clear();
// Reset number of hits.
if( localStorage.hits ) {
localStorage.hits = Number(localStorage.hits) +1;
} else {
localStorage.hits = 1;
}
document.write("Total Hits :" + localStorage.hits );
</script>
<p>Refreshing the page would not to increase hit counter.</p>
<p>Close the window and open it again and check the result.</p>
</body>
</html>
这将生成以下结果:
This will produce following result −
HTML5 - Web SQL Database
Web SQL 数据库 API 实际上并不是 HTML5 规范的一部分,但它是一个单独的规范,用于引入一组 API,使用 SQL 操纵客户端数据库。
The Web SQL Database API isn’t actually part of the HTML5 specification but it is a separate specification which introduces a set of APIs to manipulate client-side databases using SQL.
我假设你是一位优秀的 Web 开发人员,如果是这样的话,那么毫无疑问,你将非常了解 SQL 和 RDBMS 概念。如果你仍然希望使用 SQL,那么你可以通过我们的 SQL Tutorial 进行了解。
I’m assuming you are a great web developer and if that is the case then no doubt, you would be well aware of SQL and RDBMS concepts. If you still want to have a session with SQL then, you can go through our SQL Tutorial.
Web SQL 数据库将在最新版本的 Safari、Chrome 和 Opera 中运行。
Web SQL Database will work in latest version of Safari, Chrome and Opera.
The Core Methods
规范中定义了以下三种核心方法,我将在本教程中介绍:
There are following three core methods defined in the spec that I am going to cover in this tutorial −
-
openDatabase − This method creates the database object either using existing database or creating new one.
-
transaction − This method gives us the ability to control a transaction and performing either commit or rollback based on the situation.
-
executeSql − This method is used to execute actual SQL query.
Opening Database
如果数据库已存在,openDatabase 方法会处理打开数据库;如果数据库不存在,此方法将创建该数据库。
The openDatabase method takes care of opening a database if it already exists, this method will create it if it already does not exist.
要创建并打开数据库,请使用以下代码 −
To create and open a database, use the following code −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
上述方法采用了以下五个参数 −
The above method took the following five parameters −
-
Database name
-
Version number
-
Text description
-
Size of database
-
Creation callback
最后一个第 5 个参数,即 creation callback,将在创建数据库时调用。然而,如果没有该功能,仍将动态创建数据库并正确设置版本。
The last and 5th argument, creation callback will be called if the database is being created. Without this feature, however, the databases are still being created on the fly and correctly versioned.
Executing queries
要执行查询,请使用 database.transaction() 函数。此函数需要一个参数,该参数是一个函数,用于根据以下内容处理实际执行查询的操作 −
To execute a query you use the database.transaction() function. This function needs a single argument, which is a function that takes care of actually executing the query as follows −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
});
上面的查询将在“mydb”数据库中创建一个名为 LOGS 的表。
The above query will create a table called LOGS in 'mydb' database.
INSERT Operation
要向表中创建条目,我们在上述示例中添加简单的 SQL 查询,如下所示 −
To create enteries into the table we add simple SQL query in the above example as follows −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});
我们可以在创建条目时传递动态值,如下所示 −
We can pass dynamic values while creating entering as follows −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id,log) VALUES (?, ?'), [e_id, e_log];
});
这里 e_id 和 e_log 是外部变量,而 executeSql 将数组参数中的每个项目映射到“?”。
Here e_id and e_log are external variables, and executeSql maps each item in the array argument to the "?"s.
READ Operation
要读取已存在的记录,我们使用回调来捕获结果,如下所示 −
To read already existing records we use a callback to capture the results as follows −
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
});
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++) {
alert(results.rows.item(i).log );
}
}, null);
});
Final Example
最后,让我们将此示例保存在一个成熟的 HTML5 文档中,如下所示,并尝试使用 Safari 浏览器运行它。
So finally, let us keep this example in a full-fledged HTML5 document as follows and try to run it with Safari browser.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
var db = openDatabase('mydb', '1.0', 'Test DB', 2 * 1024 * 1024);
var msg;
db.transaction(function (tx) {
tx.executeSql('CREATE TABLE IF NOT EXISTS LOGS (id unique, log)');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (1, "foobar")');
tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "logmsg")');
msg = '<p>Log message created and row inserted.</p>';
document.querySelector('#status').innerHTML = msg;
})
db.transaction(function (tx) {
tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) {
var len = results.rows.length, i;
msg = "<p>Found rows: " + len + "</p>";
document.querySelector('#status').innerHTML += msg;
for (i = 0; i < len; i++) {
msg = "<p><b>" + results.rows.item(i).log + "</b></p>";
document.querySelector('#status').innerHTML += msg;
}
}, null);
});
</script>
</head>
<body>
<div id = "status" name = "status">Status Message</div>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
HTML5 - Server Sent Events
传统的 Web 应用程序生成发往 Web 服务器的事件。例如,点击链接会请求服务器提供一个新页面。
Conventional web applications generate events which are dispatched to the web server. For example, a simple click on a link requests a new page from the server.
从 Web 浏览器流向 Web 服务器的事件类型可称为客户端发送事件。
The type of events which are flowing from web browser to the web server may be called client-sent events.
与 HTML5 一起, WHATWG Web 应用程序 1.0 引入了从 Web 服务器流向 Web 浏览器的事件,它们被称为服务器发送事件 (SSE)。使用 SSE,您可以持续不断地将 DOM 事件从您的 Web 服务器推送到访问者的浏览器。
Along with HTML5, WHATWG Web Applications 1.0 introduces events which flow from web server to the web browsers and they are called Server-Sent Events (SSE). Using SSE you can push DOM events continuously from your web server to the visitor’s browser.
事件流方法会打开与服务器的持续连接,并在有新信息可用时将数据发送至客户端,从而消除持续查询的需要。
The event streaming approach opens a persistent connection to the server, sending data to the client when new information is available, eliminating the need for continuous polling.
服务器发送事件标准化了将数据从服务器流式传输到客户端的方式。
Server-sent events standardize how we stream data from the server to the client.
Web Application for SSE
要在 Web 应用程序中使用服务器发送事件,您需要将 <eventsource> 元素添加到文档。
To use Server-Sent Events in a web application, you would need to add an <eventsource> element to the document.
<eventsource> 元素的 src 属性应指向一个 URL,该 URL 应提供一个持续的 HTTP 连接,该连接发送包含事件的数据流。
The src attribute of <eventsource> element should point to an URL which should provide a persistent HTTP connection that sends a data stream containing the events.
该 URL 将指向一个 PHP、PERL 或任何 Python 脚本,该脚本将负责持续发送事件数据。以下是将期望服务器时间的 Web 应用程序的一个简单示例。
The URL would point to a PHP, PERL or any Python script which would take care of sending event data consistently. Following is a simple example of web application which would expect server time.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
/* Define event handling logic here */
</script>
</head>
<body>
<div id = "sse">
<eventsource src = "/cgi-bin/ticker.cgi" />
</div>
<div id = "ticker">
<TIME>
</div>
</body>
</html>
Server Side Script for SSE
服务器端脚本应发送 Content-type 头部并指定 text/event-stream 类型,如下所示。
A server side script should send Content-type header specifying the type text/event-stream as follows.
print "Content-Type: text/event-stream\n\n";
在设置 Content-Type 后,服务器端脚本将发送 Event : 标记,后跟事件名称。以下示例将把 Server-Time 发送为事件名称,并以一个换行符结束。
After setting Content-Type, server side script would send an Event: tag followed by event name. Following example would send Server-Time as event name terminated by a new line character.
print "Event: server-time\n";
最后一步是使用 Data : 标签发送事件数据,该标签后跟由换行符结尾的整数值或字符串值,如下所示 −
Final step is to send event data using Data: tag which would be followed by integer of string value terminated by a new line character as follows −
$time = localtime();
print "Data: $time\n";
最后,以下是由 Perl 编写的完整的 ticker.cgi:
Finally, following is complete ticker.cgi written in Perl −
#!/usr/bin/perl
print "Content-Type: text/event-stream\n\n";
while(true) {
print "Event: server-time\n";
$time = localtime();
print "Data: $time\n";
sleep(5);
}
Handle Server-Sent Events
让我们修改我们的 Web 应用程序来处理服务器发送的事件。以下是最终示例。
Let us modify our web application to handle server-sent events. Following is the final example.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
document.getElementsByTagName("eventsource")[0].addEventListener("server-time",
eventHandler, false);
function eventHandler(event) {
// Alert time sent by the server
document.querySelector('#ticker').innerHTML = event.data;
}
</script>
</head>
<body>
<div id = "sse">
<eventsource src = "/cgi-bin/ticker.cgi" />
</div>
<div id = "ticker" name = "ticker">
[TIME]
</div>
</body>
</html>
在测试 Server-Sent 事件之前,建议您确保您的网络浏览器支持此概念。
Before testing Server-Sent events, I would suggest that you make sure your web browser supports this concept.
HTML5 - WebSockets
WebSocket 是一种新一代的双向通信技术,适用于网络应用,它通过单个套接字运行,并通过符合 HTML 5 的浏览器中的 JavaScript 接口公开。
WebSockets is a next-generation bidirectional communication technology for web applications which operates over a single socket and is exposed via a JavaScript interface in HTML 5 compliant browsers.
WebSockets 一旦与 Web 服务器建立连接,就可以通过调用 send() 方法从浏览器向服务器发送数据,并通过 onmessage 事件处理程序从服务器向浏览器接收数据。
Once you get a Web Socket connection with the web server, you can send data from browser to server by calling a send() method, and receive data from server to browser by an onmessage event handler.
以下是用于创建新 WebSocket 对象的 API。
Following is the API which creates a new WebSocket object.
var Socket = new WebSocket(url, [protocal] );
这里,第一个参数 url 指明要连接的 URL。第二个属性 protocol 是可选的,如果存在,则指明服务器必须支持的子协议,以便连接成功。
Here first argument, url, specifies the URL to which to connect. The second attribute, protocol is optional, and if present, specifies a sub-protocol that the server must support for the connection to be successful.
WebSocket Attributes
以下是 WebSocket 对象的属性。假设我们已按上文所述创建了 Socket 对象 −
Following are the attribute of WebSocket object. Assuming we created Socket object as mentioned above −
Sr.No. |
Attribute & Description |
1 |
Socket.readyState The readonly attribute readyState represents the state of the connection. It can have the following values − A value of 0 indicates that the connection has not yet been established. A value of 1 indicates that the connection is established and communication is possible. A value of 2 indicates that the connection is going through the closing handshake. A value of 3 indicates that the connection has been closed or could not be opened. |
2 |
Socket.bufferedAmount The readonly attribute bufferedAmount represents the number of bytes of UTF-8 text that have been queued using send() method. |
WebSocket Events
以下是与 WebSocket 对象关联的事件。假设我们已按上文所述创建了 Socket 对象 −
Following are the events associated with WebSocket object. Assuming we created Socket object as mentioned above −
Event |
Event Handler |
Description |
open |
Socket.onopen |
This event occurs when socket connection is established. |
message |
Socket.onmessage |
This event occurs when client receives data from server. |
error |
Socket.onerror |
This event occurs when there is any error in communication. |
close |
Socket.onclose |
This event occurs when connection is closed. |
WebSocket Methods
以下是与 WebSocket 对象关联的方法。假设我们如上所述创建了 Socket 对象。
Following are the methods associated with WebSocket object. Assuming we created Socket object as mentioned above −
Sr.No. |
Method & Description |
1 |
Socket.send() The send(data) method transmits data using the connection. |
2 |
Socket.close() The close() method would be used to terminate any existing connection. |
WebSocket Example
WebSocket 是客户端和服务器之间的一个标准双向 TCP 套接字。此套接字最开始是作为 HTTP 连接,之后在 HTTP 握手后“升级”为 TCP 套接字。 handshake 完毕之后,任一端均可发送数据。
A WebSocket is a standard bidirectional TCP socket between the client and the server. The socket starts out as a HTTP connection and then "Upgrades" to a TCP socket after a HTTP handshake. After the handshake, either side can send data.
Client Side HTML & JavaScript Code
在撰写本教程时,只有少数网络浏览器支持 WebSocket() 接口。您可以尝试使用最新版本的 Chrome、Mozilla、Opera 和 Safari 来尝试以下示例。
At the time of writing this tutorial, there are only few web browsers supporting WebSocket() interface. You can try following example with latest version of Chrome, Mozilla, Opera and Safari.
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function WebSocketTest() {
if ("WebSocket" in window) {
alert("WebSocket is supported by your Browser!");
// Let us open a web socket
var ws = new WebSocket("ws://localhost:9998/echo");
ws.onopen = function() {
// Web Socket is connected, send data using send()
ws.send("Message to send");
alert("Message is sent...");
};
ws.onmessage = function (evt) {
var received_msg = evt.data;
alert("Message is received...");
};
ws.onclose = function() {
// websocket is closed.
alert("Connection is closed...");
};
} else {
// The browser doesn't support WebSocket
alert("WebSocket NOT supported by your Browser!");
}
}
</script>
</head>
<body>
<div id = "sse">
<a href = "javascript:WebSocketTest()">Run WebSocket</a>
</div>
</body>
</html>
Install pywebsocket
在测试上述客户端程序之前,需要一个支持 WebSocket 的服务器。从 pywebsocket 下载 mod_pywebsocket-x.x.x.tar.gz,其目标是为 Apache HTTP 服务器提供一个 WebSocket 扩展,并按照以下步骤进行安装。
Before you test above client program, you need a server which supports WebSocket. Download mod_pywebsocket-x.x.x.tar.gz from pywebsocket which aims to provide a Web Socket extension for Apache HTTP Server and install it following these steps.
-
Unzip and untar the downloaded file.
-
Go inside pywebsocket-x.x.x/src/ directory.
-
$python setup.py build
-
$sudo python setup.py install
-
Then read document by − $pydoc mod_pywebsocket
这会将其安装到 Python 环境中。
This will install it into your python environment.
Start the Server
转到 pywebsocket-x.x.x/src/mod_pywebsocket 文件夹,并运行以下命令 −
Go to the pywebsocket-x.x.x/src/mod_pywebsocket folder and run the following command −
$sudo python standalone.py -p 9998 -w ../example/
这将使服务器开始在端口 9998 处监听,并使用 -w 选项指定的 handlers 目录,我们的 echo_wsh.py 就驻留在该目录中。
This will start the server listening at port 9998 and use the handlers directory specified by the -w option where our echo_wsh.py resides.
现在使用 Chrome 浏览器打开您在开始时创建的 html 文件。如果您的浏览器支持 WebSocket(),那么您会收到一个提醒,指明您的浏览器支持 WebSocket,最后,当您单击“运行 WebSocket”时,您会收到服务器脚本发送的 Goodbye 消息。
Now using Chrome browser open the html file your created in the beginning. If your browser supports WebSocket(), then you would get alert indicating that your browser supports WebSocket and finally when you click on "Run WebSocket" you would get Goodbye message sent by the server script.
HTML5 - Canvas
HTML5 画布元素 <canvas> 让您可以轻松而便捷地使用 JavaScript 绘制图形。它可以用于绘制图表、制作照片合成,或进行简单(且不简单的)动画。
HTML5 element <canvas> gives you an easy and powerful way to draw graphics using JavaScript. It can be used to draw graphs, make photo compositions or do simple (and not so simple) animations.
这是一个简单的 <canvas> 元素,它只有 width 和 height 这两个特定属性,以及 id、name 和 class 等所有核心 HTML5 属性。
Here is a simple <canvas> element which has only two specific attributes width and height plus all the core HTML5 attributes like id, name and class, etc.
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
您可以使用 getElementById() 方法轻松地在 DOM 中找到 <canvas> 元素,如下所示:
You can easily find that <canvas> element in the DOM using getElementById() method as follows −
var canvas = document.getElementById("mycanvas");
让我们在 HTML5 文档中看看使用 <canvas> 元素的一个简单示例。
Let us see a simple example on using <canvas> element in HTML5 document.
<!DOCTYPE HTML>
<html>
<head>
<style>
#mycanvas{border:1px solid red;}
</style>
</head>
<body>
<canvas id = "mycanvas" width = "100" height = "100"></canvas>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
The Rendering Context
<canvas> 起初是空白的,并且为了显示内容,先要由脚本访问渲染上下文并对其进行绘制。
The <canvas> is initially blank, and to display something, a script first needs to access the rendering context and draw on it.
canvas 元素有一个名为 getContext 的 DOM 方法,用于获取渲染上下文及其绘制函数。此函数带一个参数,即上下文 2d 的类型。
The canvas element has a DOM method called getContext, used to obtain the rendering context and its drawing functions. This function takes one parameter, the type of context*2d*.
以下是获取所需上下文的代码,以及检查您的浏览器是否支持 <canvas> 元素 −
Following is the code to get required context along with a check if your browser supports <canvas> element −
var canvas = document.getElementById("mycanvas");
if (canvas.getContext) {
var ctx = canvas.getContext('2d');
// drawing code here
} else {
// canvas-unsupported code here
}
Browser Support
最新版本的 Firefox、Safari、Chrome 和 Opera 都支持 HTML5 Canvas,但 IE8 本身不支持 Canvas。
The latest versions of Firefox, Safari, Chrome and Opera all support for HTML5 Canvas but IE8 does not support canvas natively.
您可以使用 ExplorerCanvas 让 canvas 通过 Internet Explorer 获得支持。您只需要按如下所示,包含 JavaScript −
You can use ExplorerCanvas to have canvas support through Internet Explorer. You just need to include this JavaScript as follows −
<!--[if IE]><script src = "excanvas.js"></script><![endif]-->
HTML5 Canvas Examples
本教程涵盖了与 HTML5 <canvas> 元素有关的以下示例。
This tutorial covers the following examples related to HTML5 <canvas> element.
Sr.No. |
Examples & Description |
1 |
Drawing RectanglesLearn how to draw rectangle using HTML5 <canvas> element |
2 |
Drawing PathsLearn how to make shapes using paths in HTML5 <canvas> element |
3 |
Drawing LinesLearn how to draw lines using HTML5 <canvas> element |
4 |
Drawing BezierLearn how to draw Bezier curve using HTML5 <canvas> element |
5 |
Drawing QuadraticLearn how to draw quadratic curve using HTML5 <canvas> element |
6 |
Using ImagesLearn how to use images with HTML5 <canvas> element |
7 |
Create GradientsLearn how to create gradients using HTML5 <canvas> element |
8 |
Styles and ColorsLearn how to apply styles and colors using HTML5 <canvas> element |
9 |
Text and FontsLearn how to draw amazing text using different fonts and their size. |
10 |
Pattern and ShadowLearn how to draw different patterns and drop shadows. |
11 |
Canvas StatesLearn how to save and restore canvas states while doing complex drawings on a canvas. |
12 |
Canvas TranslationThis method is used to move the canvas and its origin to a different point in the grid. |
13 |
Canvas RotationThis method is used to rotate the canvas around the current origin. |
14 |
Canvas ScalingThis method is used to increase or decrease the units in a canvas grid. |
15 |
Canvas TransformThese methods allow modifications directly to the transformation matrix. |
16 |
Canvas CompositionThis method is used to mask off certain areas or clear sections from the canvas. |
17 |
Canvas AnimationLearn how to create basic animation using HTML5 canvas and JavaScript. |
HTML5 - Audio & Video
HTML5 的功能包括原生音频和视频支持,无需 Flash。
HTML5 features include native audio and video support without the need for Flash.
HTML5 <audio> 和 <video> 标记可轻松地向网站中添加媒体。需要设置 src 属性来标识媒体源并包括一个控件属性,以便用户可以播放和暂停媒体。
The HTML5 <audio> and <video> tags make it simple to add media to a website. You need to set src attribute to identify the media source and include a controls attribute so the user can play and pause the media.
Embedding Video
以下是在网页中嵌入视频文件的简单形式 −
Here is the simplest form of embedding a video file in your webpage −
<video src = "foo.mp4" width = "300" height = "200" controls>
Your browser does not support the <video> element.
</video>
当前的 HTML5 草稿规范未指定浏览器应该在 video 标记中支持哪些视频格式。但最常用的视频格式是 −
The current HTML5 draft specification does not specify which video formats browsers should support in the video tag. But most commonly used video formats are −
-
Ogg − Ogg files with Thedora video codec and Vorbis audio codec.
-
mpeg4 − MPEG4 files with H.264 video codec and AAC audio codec.
你可以使用 <source> 标签来指定媒体及其媒体类型及许多其他属性。一个 video 元素允许包含多个 source 元素,浏览器会使用第一个识别的格式 −
You can use <source> tag to specify media along with media type and many other attributes. A video element allows multiple source elements and browser will use the first recognized format −
<!DOCTYPE HTML>
<html>
<body>
<video width = "300" height = "200" controls autoplay>
<source src = "/html5/foo.ogg" type ="video/ogg" />
<source src = "/html5/foo.mp4" type = "video/mp4" />
Your browser does not support the <video> element.
</video>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
Video Attribute Specification
HTML5 video 标签可以有许多属性来控制控件的外观和感受以及各种功能 −
The HTML5 video tag can have a number of attributes to control the look and feel and various functionalities of the control −
Sr.No. |
Attribute & Description |
1 |
autoplay This Boolean attribute if specified, the video will automatically begin to play back as soon as it can do so without stopping to finish loading the data. |
2 |
autobuffer This Boolean attribute if specified, the video will automatically begin buffering even if it’s not set to automatically play. |
3 |
controls If this attribute is present, it will allow the user to control video playback, including volume, seeking, and pause/resume playback. |
4 |
height This attribute specifies the height of the video’s display area, in CSS pixels. |
5 |
loop This Boolean attribute if specified, will allow video automatically seek back to the start after reaching at the end. |
6 |
preload This attribute specifies that the video will be loaded at page load, and ready to run. Ignored if autoplay is present. |
7 |
poster This is a URL of an image to show until the user plays or seeks. |
8 |
src The URL of the video to embed. This is optional; you may instead use the <source> element within the video block to specify the video to embed. |
9 |
width This attribute specifies the width of the video’s display area, in CSS pixels. |
Embedding Audio
HTML5 支持 <audio> 标签,该标签用于在 HTML 或 XHTML 文档中嵌入声音内容,如下所示。
HTML5 supports <audio> tag which is used to embed sound content in an HTML or XHTML document as follows.
<audio src = "foo.wav" controls autoplay>
Your browser does not support the <audio> element.
</audio>
当前的 HTML5 草案规范没有指定浏览器在 audio 标签中应该支持哪些音频格式。但最常用的音频格式是 ogg, mp3 和 wav 。
The current HTML5 draft specification does not specify which audio formats browsers should support in the audio tag. But most commonly used audio formats are ogg, mp3 and wav.
你可以使用 <source&ggt; 标签来指定媒体及其媒体类型及许多其他属性。一个 audio 元素允许包含多个 source 元素,浏览器会使用第一个识别的格式 −
You can use <source&ggt; tag to specify media along with media type and many other attributes. An audio element allows multiple source elements and browser will use the first recognized format −
<!DOCTYPE HTML>
<html>
<body>
<audio controls autoplay>
<source src = "/html5/audio.ogg" type = "audio/ogg" />
<source src = "/html5/audio.wav" type = "audio/wav" />
Your browser does not support the <audio> element.
</audio>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
Audio Attribute Specification
HTML5 audio 标签可以有许多属性来控制控件的外观和感受以及各种功能 −
The HTML5 audio tag can have a number of attributes to control the look and feel and various functionalities of the control −
Sr.No. |
Attribute & Description |
1 |
autoplay This Boolean attribute if specified, the audio will automatically begin to play back as soon as it can do so without stopping to finish loading the data. |
2 |
autobuffer This Boolean attribute if specified, the audio will automatically begin buffering even if it’s not set to automatically play. |
3 |
controls If this attribute is present, it will allow the user to control audio playback, including volume, seeking, and pause/resume playback. |
4 |
loop This Boolean attribute if specified, will allow audio automatically seek back to the start after reaching at the end. |
5 |
preload This attribute specifies that the audio will be loaded at page load, and ready to run. Ignored if autoplay is present. |
6 |
src The URL of the audio to embed. This is optional; you may instead use the <source> element within the video block to specify the video to embed. |
Handling Media Events
HTML5 音频和视频标记可以具有多个属性来控制使用 JavaScript 的各种控件功能 −
The HTML5 audio and video tag can have a number of attributes to control various functionalities of the control using JavaScript −
S.No. |
Event & Description |
1 |
abort This event is generated when playback is aborted. |
2 |
canplay This event is generated when enough data is available that the media can be played. |
3 |
ended This event is generated when playback completes. |
4 |
error This event is generated when an error occurs. |
5 |
loadeddata This event is generated when the first frame of the media has finished loading. |
6 |
loadstart This event is generated when loading of the media begins. |
7 |
pause This event is generated when playback is paused. |
8 |
play This event is generated when playback starts or resumes. |
9 |
progress This event is generated periodically to inform the progress of the downloading the media. |
10 |
ratechange This event is generated when the playback speed changes. |
11 |
seeked This event is generated when a seek operation completes. |
12 |
seeking This event is generated when a seek operation begins. |
13 |
suspend This event is generated when loading of the media is suspended. |
14 |
volumechange This event is generated when the audio volume changes. |
15 |
waiting This event is generated when the requested operation (such as playback) is delayed pending the completion of another operation (such as a seek). |
以下是一个允许播放给定视频的示例 −
Following is the example which allows to play the given video −
<!DOCTYPE HTML>
<html>
<head>
<script type = "text/javascript">
function PlayVideo() {
var v = document.getElementsByTagName("video")[0];
v.play();
}
</script>
</head>
<body>
<form>
<video width = "300" height = "200" src = "/html5/foo.mp4">
Your browser does not support the video element.
</video>
<br />
<input type = "button" onclick = "PlayVideo();" value = "Play"/>
</form>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
Configuring Servers for Media Type
大多数服务器默认情况下不会使用正确的 MIME 类型提供 Ogg 或 mp4 媒体,因此你可能需要为此添加适当的配置。
Most servers don’t by default serve Ogg or mp4 media with the correct MIME types, so you’ll likely need to add the appropriate configuration for this.
AddType audio/ogg .oga
AddType audio/wav .wav
AddType video/ogg .ogv .ogg
AddType video/mp4 .mp4
HTML5 - Geolocation
HTML5 地理位置 API 让你可以与你喜欢的网站共享你的位置。一个 JavaScript 可以获取你的纬度和经度,并可发送到后端 Web 服务器,并执行精美的基于位置的操作,如查找当地企业或在地图上显示你的位置。
HTML5 Geolocation API lets you share your location with your favorite web sites. A JavaScript can capture your latitude and longitude and can be sent to backend web server and do fancy location-aware things like finding local businesses or showing your location on a map.
现今,大多数浏览器和移动设备都支持地理位置 API。地理位置 API 使用全局导航器对象的某个新属性,即可以如下所示创建的地理位置对象 −
Today most of the browsers and mobile devices support Geolocation API. The geolocation APIs work with a new property of the global navigator object ie. Geolocation object which can be created as follows −
var geolocation = navigator.geolocation;
地理位置对象是一个允许小组件检索有关设备地理位置信息的服务对象。
The geolocation object is a service object that allows widgets to retrieve information about the geographic location of the device.
Geolocation Methods
地理位置对象提供了以下方法 −
The geolocation object provides the following methods −
Sr.No. |
Method & Description |
1 |
getCurrentPosition()This method retrieves the current geographic location of the user. |
2 |
watchPosition()This method retrieves periodic updates about the current geographic location of the device. |
3 |
clearWatch()This method cancels an ongoing watchPosition call. |
Example
以下是一个示例代码,用于使用上述任何方法 −
Following is a sample code to use any of the above method −
function getLocation() {
var geolocation = navigator.geolocation;
geolocation.getCurrentPosition(showLocation, errorHandler);
}
在这里,showLocation 和 errorHandler 是一些回调方法,它们会像下一节中解释的那样,被用来获取实际位置,以及在有错误的时候处理错误。
Here showLocation and errorHandler are callback methods which would be used to get actual position as explained in next section and to handle errors if there is any.
Location Properties
地理位置方法 getCurrentPosition() 和 getPositionUsingMethodName() 指定检索位置信息的回调方法。这些方法使用存储完整位置信息的 Position 对象异步调用。
Geolocation methods getCurrentPosition() and getPositionUsingMethodName() specify the callback method that retrieves the location information. These methods are called asynchronously with an object Position which stores the complete location information.
Position 对象指定了设备当前的地理位置。位置被表示成一组地理坐标,以及关于航向和速度的信息。
The Position object specifies the current geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed.
下表描述了位置对象的属性。对于可选属性,如果系统无法提供一个值,那么属性的值就会被设置为 null。
The following table describes the properties of the Position object. For the optional properties if the system cannot provide a value, the value of the property is set to null.
Property |
Type |
Description |
coords |
objects |
Specifies the geographic location of the device. The location is expressed as a set of geographic coordinates together with information about heading and speed. |
coords.latitude |
Number |
Specifies the latitude estimate in decimal degrees. The value range is [-90.00, +90.00]. |
coords.longitude |
Number |
Specifies the longitude estimate in decimal degrees. The value range is [-180.00, +180.00]. |
coords.altitude |
Number |
[Optional] Specifies the altitude estimate in meters above the WGS 84 ellipsoid. |
coords.accuracy |
Number |
[Optional] Specifies the accuracy of the latitude and longitude estimates in meters. |
coords.altitudeAccuracy |
Number |
[Optional] Specifies the accuracy of the altitude estimate in meters. |
coords.heading |
Number |
[Optional] Specifies the device’s current direction of movement in degrees counting clockwise relative to true north. |
coords.speed |
Number |
[Optional] Specifies the device’s current ground speed in meters per second. |
timestamp |
date |
Specifies the time when the location information was retrieved and the Position object created. |
Handling Errors
地理位置很复杂,很有必要抓住任何错误并巧妙地处理它。
Geolocation is complicated, and it is very much required to catch any error and handle it gracefully.
getCurrentPosition() 和 watchPosition() 地理定位方法使用一個錯誤處理回呼方法,這給出了 PositionError 物件。這個物件擁有下列兩個屬性 −
The geolocations methods getCurrentPosition() and watchPosition() make use of an error handler callback method which gives PositionError object. This object has following two properties −
Property |
Type |
Description |
code |
Number |
Contains a numeric code for the error. |
message |
String |
Contains a human-readable description of the error. |
下表描述了在位置错误对象中返回的错误代码。
The following table describes the possible error codes returned in the PositionError object.
Code |
Constant |
Description |
0 |
UNKNOWN_ERROR |
The method failed to retrieve the location of the device due to an unknown error. |
1 |
PERMISSION_DENIED |
The method failed to retrieve the location of the device because the application does not have permission to use the Location Service. |
2 |
POSITION_UNAVAILABLE |
The location of the device could not be determined. |
3 |
TIMEOUT |
The method was unable to retrieve the location information within the specified maximum timeout interval. |
Position Options
以下為 getCurrentPosition() 方法的實際語法 −
Following is the actual syntax of getCurrentPosition() method −
getCurrentPosition(callback, ErrorCallback, options)
这里的第三个参数是 PositionOptions 对象,它指定了一组用于检索设备地理位置的选项。
Here third argument is the PositionOptions object which specifies a set of options for retrieving the geographic location of the device.
以下是可以作為第三個參數指定的選項 −
Following are the options which can be specified as third argument −
Property |
Type |
Description |
enableHighAccuracy |
Boolean |
Specifies whether the widget wants to receive the most accurate location estimate possible. By default this is false. |
timeout |
Number |
The timeout property is the number of milliseconds your web application is willing to wait for a position. |
maximumAge |
Number |
Specifies the expiry time in milliseconds for cached location information. |
HTML5 - Microdata
Microdata 是一種標準化方式,在網路上提供附加語意。
Microdata is a standardized way to provide additional semantics in your web pages.
Microdata 讓您可以定義自訂元素,並開始在網頁中嵌入自訂屬性。在較高階層中,microdata 包含一組名稱-值對。
Microdata lets you define your own customized elements and start embedding custom properties in your web pages. At a high level, microdata consists of a group of name-value pairs.
这些组称为 items ,每个名称-值对是 property 。项目和属性由常规元素表示。
The groups are called items, and each name-value pair is a property. Items and properties are represented by regular elements.
Example
-
To create an item, the itemscope attribute is used.
-
To add a property to an item, the itemprop attribute is used on one of the item’s descendants.
這裡有兩個項目,每個項目都有「名稱」屬性 −
Here there are two items, each of which has the property "name" −
<html>
<body>
<div itemscope>
<p>My name is <span itemprop = "name">Zara</span>.</p>
</div>
<div itemscope>
<p>My name is <span itemprop = "name">Nuha</span>.</p>
</div>
</body>
</html>
它将产生以下结果 −
It will produce the following result −
属性通常具有字符串值,但它可以具有以下数据类型 −
Properties generally have values that are strings but it can have following data types −
Global Attributes
Microdata 引入了五个全局属性,任何元素都可以使用这些属性,并为机器提供有关数据的上下文。
Microdata introduces five global attributes which would be available for any element to use and give context for machines about your data.
Sr.No. |
Attribute & Description |
1 |
itemscope This is used to create an item. The itemscope attribute is a Boolean attribute that tells that there is Microdata on this page, and this is where it starts. |
2 |
itemtype This attribute is a valid URL which defines the item and provides the context for the properties. |
3 |
itemid This attribute is global identifier for the item. |
4 |
itemprop This attribute defines a property of the item. |
5 |
itemref This attribute gives a list of additional elements to crawl to find the name-value pairs of the item. |
Properties Datatypes
如上例中所述,属性通常具有字符串值,但它们也可能具有 URL 值。以下示例具有一个属性“image”,其值为一个 URL −
Properties generally have values that are strings as mentioned in above example but they can also have values that are URLs. Following example has one property, "image", whose value is a URL −
<div itemscope>
<img itemprop = "image" src = "tp-logo.gif" alt = "TutorialsPoint">
</div>
属性的值也可以是日期、时间或日期和时间。这是使用 time 元素及其 datetime 属性实现的。
Properties can also have values that are dates, times, or dates and times. This is achieved using the time element and its datetime attribute.
<html>
<body>
<div itemscope>
My birthday is:
<time itemprop = "birthday" datetime = "1971-05-08">
Aug 5th 1971
</time>
</div>
</body>
</html>
它将产生以下结果 −
It will produce the following result −
属性本身也可以是名称-值对的组,方法是在声明属性的元素上放置 itemscope 属性。
Properties can also themselves be groups of name-value pairs, by putting the itemscope attribute on the element that declares the property.
Microdata API support
如果浏览器支持 HTML5 microdata API,则全局文档对象上将有 getItems() 函数。如果浏览器不支持 microdata,则 getItems() 函数将未定义。
If a browser supports the HTML5 microdata API, there will be a getItems() function on the global document object. If browser doesn’t support microdata, the getItems() function will be undefined.
function supports_microdata_api() {
return !!document.getItems;
}
Modernizr 尚未支援檢查 microdata API,所以您需要使用類似上面所列出的函式。
Modernizr does not yet support checking for the microdata API, so you’ll need to use the function like the one listed above.
HTML5 microdata 标准包括 HTML 标记(主要用于搜索引擎)和一组 DOM 函数(主要用于浏览器)。
The HTML5 microdata standard includes both HTML markup (primarily for search engines) and a set of DOM functions (primarily for browsers).
您可以在網頁中包含 microdata 標記,而無法理解 microdata 屬性的搜尋引擎只會忽略它們。但是如果您需要透過 DOM 存取或操作 microdata,您需要檢查瀏覽器是否支援 microdata DOM API。
You can include microdata markup in your web pages, and search engines that don’t understand the microdata attributes will just ignore them. But if you need to access or manipulate microdata through the DOM, you’ll need to check whether the browser supports the microdata DOM API.
Defining Microdata Vocabulary
要定義 microdata 詞彙,您需要一個指向作業中的網頁的命名空間 URL。例如,[role="bare"] [role="bare"]https://data-vocabulary.org/Person 可用於擁有下列命名屬性之個人 microdata 詞彙的命名空間 −
To define microdata vocabulary you need a namespace URL which points to a working web page. For example [role="bare"]https://data-vocabulary.org/Person can be used as the namespace for a personal microdata vocabulary with the following named properties −
-
name − Person name as a simple string
-
Photo − A URL to a picture of the person.
-
URL − A website belonging to the person.
关于属性:人微数据可以用以下方式表达 −
Using about properties a person microdata could be as follows −
<html>
<body>
<div itemscope>
<section itemscope itemtype = "http://data-vocabulary.org/Person">
<h1 itemprop = "name">Gopal K Varma</h1>
<p>
<img itemprop = "photo"
src = "http://www.tutorialspoint.com/green/images/logo.png">
</p>
<a itemprop = "url" href = "#">Site</a>
</section>
</div>
</body>
</html>
它将产生以下结果 −
It will produce the following result −
Google 支援 microdata 作為其「豐富片段」程式的一部分。當 Google 的網路爬蟲分析您的網頁並找到符合 [role="bare"] [role="bare"]http://datavocabulary.org/Person 詞彙的 microdata 屬性時,它會剖析這些屬性並將它們儲存於網頁資料的其餘部分。
Google supports microdata as part of their Rich Snippets program. When Google’s web crawler parses your page and finds microdata properties that conform to the [role="bare"]http://datavocabulary.org/Person vocabulary, it parses out those properties and stores them alongside the rest of the page data.
您可以使用 Rich Snippets Testing 工具測試上述範例,使用 [role="bare"] [role="bare"]http://www.tutorialspoint.com/html5/microdata.htm
You can test above example using Rich Snippets Testing Tool using [role="bare"]http://www.tutorialspoint.com/html5/microdata.htm
關於 Microdata 的進一步開發,您可以隨時參照 HTML5 Microdata 。
For further development on Microdata you can always refer to HTML5 Microdata.
HTML5 - Drag & drop
拖放 (DnD) 是強大的使用者介面概念,它使您可以輕鬆地使用滑鼠按鍵複製、重新排序與刪除項目。這允許使用者按一下並按住元素上的滑鼠按鍵,將它拖曳到另一個位置,然後放開滑鼠按鍵將元素放到那裡。
Drag and Drop (DnD) is powerful User Interface concept which makes it easy to copy, reorder and deletion of items with the help of mouse clicks. This allows the user to click and hold the mouse button down over an element, drag it to another location, and release the mouse button to drop the element there.
要使用傳統的 HTML4 完成拖放功能,開發人員必須使用複雜的 JavaScript 程式設計或其他 JavaScript 框架,例如 jQuery 等。
To achieve drag and drop functionality with traditional HTML4, developers would either have to either have to use complex JavaScript programming or other JavaScript frameworks like jQuery etc.
現在 HTML 5 提出一個拖放 (DnD) API,它為瀏覽器帶來原生 DnD 支援,使編碼變得更容易。
Now HTML 5 came up with a Drag and Drop (DnD) API that brings native DnD support to the browser making it much easier to code up.
所有主流浏览器(如 Chrome、Firefox 3.5 和 Safari 4 等)都支持 HTML 5 DnD。
HTML 5 DnD is supported by all the major browsers like Chrome, Firefox 3.5 and Safari 4 etc.
Drag and Drop Events
在拖放操作的各个阶段都会触发一些事件。以下列出了这些事件:
There are number of events which are fired during various stages of the drag and drop operation. These events are listed below −
Sr.No. |
Events & Description |
1 |
dragstart Fires when the user starts dragging of the object. |
2 |
dragenter Fired when the mouse is first moved over the target element while a drag is occurring. A listener for this event should indicate whether a drop is allowed over this location. If there are no listeners, or the listeners perform no operations, then a drop is not allowed by default. |
3 |
dragover This event is fired as the mouse is moved over an element when a drag is occurring. Much of the time, the operation that occurs during a listener will be the same as the dragenter event. |
4 |
dragleave This event is fired when the mouse leaves an element while a drag is occurring. Listeners should remove any highlighting or insertion markers used for drop feedback. |
5 |
drag Fires every time the mouse is moved while the object is being dragged. |
6 |
drop The drop event is fired on the element where the drop was occurred at the end of the drag operation. A listener would be responsible for retrieving the data being dragged and inserting it at the drop location. |
7 |
dragend Fires when the user releases the mouse button while dragging an object. |
Note − 请注意,只触发拖动事件;在拖动操作期间不触发鼠标事件,例如 mousemove。
Note − Note that only drag events are fired; mouse events such as mousemove are not fired during a drag operation.
The DataTransfer Object
所有拖放事件的事件监听器方法都接受 Event 对象,该对象有一个只读属性,称为 dataTransfer 。
The event listener methods for all the drag and drop events accept Event object which has a readonly attribute called dataTransfer.
event.dataTransfer 返回与事件关联的 DataTransfer 对象,如下所示:
The event.dataTransfer returns DataTransfer object associated with the event as follows −
function EnterHandler(event) {
DataTransfer dt = event.dataTransfer;
.............
}
DataTransfer 对象保存有关拖放操作的数据。这些数据可以通过与 DataTransfer 对象关联的各种属性进行检索和设置,如下所示:
The DataTransfer object holds data about the drag and drop operation. This data can be retrieved and set in terms of various attributes associated with DataTransfer object as explained below −
Sr.No. |
DataTransfer attributes and their description |
1 |
dataTransfer.dropEffect [ = value ] Returns the kind of operation that is currently selected. This attribute can be set, to change the selected operation. The possible values are none, copy, link, and move. |
2 |
dataTransfer.effectAllowed [ = value ] Returns the kinds of operations that are to be allowed. This attribute can be set, to change the allowed operations. The possible values are none, copy, copyLink, copyMove, link, linkMove, move, all and uninitialized. |
3 |
dataTransfer.types Returns a DOMStringList listing the formats that were set in the dragstart event. In addition, if any files are being dragged, then one of the types will be the string "Files". |
4 |
dataTransfer.clearData ( [ format ] ) Removes the data of the specified formats. Removes all data if the argument is omitted. |
5 |
dataTransfer.setData(format, data) Adds the specified data. |
6 |
data = dataTransfer.getData(format) Returns the specified data. If there is no such data, returns the empty string. |
7 |
dataTransfer.files Returns a FileList of the files being dragged, if any. |
8 |
dataTransfer.setDragImage(element, x, y) Uses the given element to update the drag feedback, replacing any previously specified feedback. |
9 |
dataTransfer.addElement(element) Adds the given element to the list of elements used to render the drag feedback. |
Drag and Drop Process
以下是实现拖放操作的步骤−
Following are the steps to be carried out to implement Drag and Drop operation −
Step 1 - Making an Object Draggable
以下是需要采取的步骤−
Here are steps to be taken −
-
If you want to drag an element, you need to set the draggable attribute to true for that element.
-
Set an event listener for dragstart that stores the data being dragged.
-
The event listener dragstart will set the allowed effects (copy, move, link, or some combination).
以下是使对象可拖动的示例−
Following is the example to make an object draggable −
<!DOCTYPE HTML>
<html>
<head>
<style type = "text/css">
#boxA, #boxB {
float:left;padding:10px;margin:10px; -moz-user-select:none;
}
#boxA { background-color: #6633FF; width:75px; height:75px; }
#boxB { background-color: #FF6699; width:150px; height:150px; }
</style>
<script type = "text/javascript">
function dragStart(ev) {
ev.dataTransfer.effectAllowed = 'move';
ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
ev.dataTransfer.setDragImage(ev.target,0,0);
return true;
}
</script>
</head>
<body>
<center>
<h2>Drag and drop HTML5 demo</h2>
<div>Try to drag the purple box around.</div>
<div id = "boxA" draggable = "true"
ondragstart = "return dragStart(ev)">
<p>Drag Me</p>
</div>
<div id = "boxB">Dustbin</div>
</center>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
Step 2 - Dropping the Object
为了接受一个拖放,拖放目标至少要监听三个事件。
To accept a drop, the drop target has to listen to at least three events.
-
The dragenter event, which is used to determine whether or not the drop target is to accept the drop. If the drop is to be accepted, then this event has to be canceled.
-
The dragover event, which is used to determine what feedback is to be shown to the user. If the event is canceled, then the feedback (typically the cursor) is updated based on the dropEffect attribute’s value.
-
Finally, the drop event, which allows the actual drop to be performed.
以下是将对象拖放到另一个对象中的示例−
Following is the example to drop an object into another object −
<html>
<head>
<style type="text/css">
#boxA, #boxB {
float:left;padding:10px;margin:10px;-moz-user-select:none;
}
#boxA { background-color: #6633FF; width:75px; height:75px; }
#boxB { background-color: #FF6699; width:150px; height:150px; }
</style>
<script type="text/javascript">
function dragStart(ev) {
ev.dataTransfer.effectAllowed='move';
ev.dataTransfer.setData("Text", ev.target.getAttribute('id'));
ev.dataTransfer.setDragImage(ev.target,0,0);
return true;
}
function dragEnter(ev) {
event.preventDefault();
return true;
}
function dragOver(ev) {
return false;
}
function dragDrop(ev) {
var src = ev.dataTransfer.getData("Text");
ev.target.appendChild(document.getElementById(src));
ev.stopPropagation();
return false;
}
</script>
</head>
<body>
<center>
<h2>Drag and drop HTML5 demo</h2>
<div>Try to move the purple box into the pink box.</div>
<div id="boxA" draggable="true" ondragstart="return dragStart(event)">
<p>Drag Me</p>
</div>
<div id="boxB" ondragenter="return dragEnter(event)" ondrop="return dragDrop(event)" ondragover="return dragOver(event)">Dustbin</div>
</center>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
HTML5 - Web Workers
JavaScript 是设计为在单线程环境中运行的,这意味着多个脚本无法同时运行。考虑一下你需要处理 UI 事件、查询和处理大量 API 数据以及操作 DOM 的情形。
JavaScript was designed to run in a single-threaded environment, meaning multiple scripts cannot run at the same time. Consider a situation where you need to handle UI events, query and process large amounts of API data, and manipulate the DOM.
在 CPU 利用率高的情况下,JavaScript 将冻结你的浏览器。让我们举一个 JavaScript 执行一个大循环的简单示例−
JavaScript will hang your browser in situation where CPU utilization is high. Let us take a simple example where JavaScript goes through a big loop −
<!DOCTYPE HTML>
<html>
<head>
<title>Big for loop</title>
<script>
function bigLoop() {
for (var i = 0; i <= 10000; i += 1) {
var j = i;
}
alert("Completed " + j + "iterations" );
}
function sayHello(){
alert("Hello sir...." );
}
</script>
</head>
<body>
<input type = "button" onclick = "bigLoop();" value = "Big Loop" />
<input type = "button" onclick = "sayHello();" value = "Say Hello" />
</body>
</html>
它将产生以下结果 −
It will produce the following result −
当您单击 Big Loop 按钮时,它会在 Firefox 中显示以下结果:
When you click Big Loop button it displays following result in Firefox −
What is Web Workers?
在没有打断用户界面,且通常在单独线程上运行的情况下,通过使用 {s0} 能够处理上面解释的情况。
The situation explained above can be handled using Web Workers who will do all the computationally expensive tasks without interrupting the user interface and typically run on separate threads.
Web Workers 允许运行长期脚本,这些脚本不会被响应点击或其他用户交互的脚本打断,并且允许执行长期任务而不会让步以保持页面响应。
Web Workers allow for long-running scripts that are not interrupted by scripts that respond to clicks or other user interactions, and allows long tasks to be executed without yielding to keep the page responsive.
Web Workers 是后台脚本,它们的权重大,并不适合大量使用。例如,对 400 万像素图像的每个像素启动一个工作程序是不合适的。
Web Workers are background scripts and they are relatively heavy-weight, and are not intended to be used in large numbers. For example, it would be inappropriate to launch one worker for each pixel of a four megapixel image.
脚本在 Web Worker 内部执行时,无法访问网页的窗口对象(window.document),这意味着 Web Workers 无法直接访问网页和 DOM API。尽管 Web Workers 无法阻止浏览器 UI,但它们仍会消耗 CPU 周期,降低系统的响应能力。
When a script is executing inside a Web Worker it cannot access the web page’s window object (window.document), which means that Web Workers don’t have direct access to the web page and the DOM API. Although Web Workers cannot block the browser UI, they can still consume CPU cycles and make the system less responsive.
How Web Workers Work?
Web Workers 使用 JavaScript 文件的 URL 初始化,其中包含 worker 将执行的代码。此代码设置事件侦听器,并与从主页面生成它的脚本进行通信。以下是简单的语法:
Web Workers are initialized with the URL of a JavaScript file, which contains the code the worker will execute. This code sets event listeners and communicates with the script that spawned it from the main page. Following is the simple syntax −
var worker = new Worker('bigLoop.js');
如果指定的 javascript 文件存在,浏览器将生成一个新的 worker 线程,该线程异步下载。如果您的 worker 的路径返回 404 错误,worker 将在不发出提示的情况下失败。
If the specified javascript file exists, the browser will spawn a new worker thread, which is downloaded asynchronously. If the path to your worker returns an 404 error, the worker will fail silently.
如果您的应用程序有多个支持的 JavaScript 文件,您可以使用 {s1} 方法导入它们,该方法将文件名(以逗号分隔)作为参数,如下所示:
If your application has multiple supporting JavaScript files, you can import them importScripts() method which takes file name(s) as argument separated by comma as follows −
importScripts("helper.js", "anotherHelper.js");
Web Worker 生成后,web worker 和其父页面之间的通信使用 {s2} 方法完成。根据您的浏览器/版本,postMessage() 可以将字符串或 JSON 对象作为其单个参数。
Once the Web Worker is spawned, communication between web worker and its parent page is done using the postMessage() method. Depending on your browser/version, postMessage() can accept either a string or JSON object as its single argument.
Web Worker 传递的消息使用 {s3} 在主页面中获取事件。现在让我们使用 Web Worker 编写我们的 bigLoop 示例。以下是主页面(hello.htm),它将生成一个 web worker 来执行循环并返回变量 j 的最终值:
Message passed by Web Worker is accessed using onmessage event in the main page. Now let us write our bigLoop example using Web Worker. Below is the main page (hello.htm) which will spawn a web worker to execute the loop and to return the final value of variable*j* −
<!DOCTYPE HTML>
<html>
<head>
<title>Big for loop</title>
<script>
var worker = new Worker('bigLoop.js');
worker.onmessage = function (event) {
alert("Completed " + event.data + "iterations" );
};
function sayHello() {
alert("Hello sir...." );
}
</script>
</head>
<body>
<input type = "button" onclick = "sayHello();" value = "Say Hello"/>
</body>
</html>
以下是 bigLoop.js 文件的内容。这利用 {s4} API 将通信传递回主页面:
Following is the content of bigLoop.js file. This makes use of postMessage() API to pass the communication back to main page −
for (var i = 0; i <= 1000000000; i += 1) {
var j = i;
}
postMessage(j);
这会产生以下结果 −
This will produce the following result −
Stopping Web Workers
网络工作者不会自行停止,但启动它们的页面可以通过调用 terminate() 方法来停止它们。
Web Workers don’t stop by themselves but the page that started them can stop them by calling terminate() method.
worker.terminate();
已终止的 Web Worker 将不再响应消息或执行任何其他计算。您无法重新启动一个 worker;而您能够使用相同的 URL 创建一个新的 worker。
A terminated Web Worker will no longer respond to messages or perform any additional computations. You cannot restart a worker; instead, you can create a new worker using the same URL.
Handling Errors
以下显示了 Web Worker JavaScript 文件中错误处理函数的示例,该函数将错误记录到控制台中。使用错误处理代码,上面的示例将变为以下形式:
The following shows an example of an error handling function in a Web Worker JavaScript file that logs errors to the console. With error handling code, above example would become as following −
<!DOCTYPE HTML>
<html>
<head>
<title>Big for loop</title>
<script>
var worker = new Worker('bigLoop.js');
worker.onmessage = function (event) {
alert("Completed " + event.data + "iterations" );
};
worker.onerror = function (event) {
console.log(event.message, event);
};
function sayHello() {
alert("Hello sir...." );
}
</script>
</head>
<body>
<input type = "button" onclick = "sayHello();" value = "Say Hello"/>
</body>
</html>
Checking for Browser Support
以下是在浏览器中检测 Web Worker 的功能支持的语法:
Following is the syntax to detect a Web Worker feature support available in a browser −
<!DOCTYPE HTML>
<html>
<head>
<title>Big for loop</title>
<script src = "/js/modernizr-1.5.min.js"></script>
<script>
function myFunction() {
if (Modernizr.webworkers) {
alert("Congratulation!! you have web workers support." );
} else {
alert("Sorry!! you do not have web workers support." );
}
}
</script>
</head>
<body>
<button onclick = "myFunction()">Click me</button>
</body>
</html>
这会产生以下结果 −
This will produce the following result −
HTML5 - IndexedDB
indexeddb 是一个新的 HTML5 概念,用于存储用户浏览器中的数据。与本地存储相比,indexeddb 更强大,对于需要存储大量数据的应用程序很有用。这些应用程序可以更高效地运行,并且加载速度更快。
The indexeddb is a new HTML5 concept to store the data inside user’s browser. indexeddb is more power than local storage and useful for applications that requires to store large amount of the data. These applications can run more efficiency and load faster.
Why to use indexeddb?
W3C 已宣布 Web SQL 数据库是一个已弃用的本地存储规范,因此 Web 开发人员不应再使用此技术。indexeddb 是 Web SQL 数据库的一个替代方案,比旧技术更有效。
The W3C has announced that the Web SQL database is a deprecated local storage specification so web developer should not use this technology any more. indexeddb is an alternative for web SQL data base and more effective than older technologies.
Features
-
it stores key-pair values
-
it is not a relational database
-
IndexedDB API is mostly asynchronous
-
it is not a structured query language
-
it has supported to access the data from same domain
IndexedDB
在进入一个已索引的数据库之前,我们需要添加一些实现的前缀,如下所示
Before enter into an indexeddb, we need to add some prefixes of implementation as shown below
window.indexedDB = window.indexedDB || window.mozIndexedDB || window.webkitIndexedDB ||
window.msIndexedDB;
window.IDBTransaction = window.IDBTransaction || window.webkitIDBTransaction ||
window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange ||
window.webkitIDBKeyRange || window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
Open an IndexedDB database
在创建数据库之前,我们必须为数据库准备一些数据。让我们从公司员工详细信息开始。
Before creating a database, we have to prepare some data for the data base.let’s start with company employee details.
const employeeData = [
{ id: "01", name: "Gopal K Varma", age: 35, email: "contact@tutorialspoint.com" },
{ id: "02", name: "Prasad", age: 24, email: "prasad@tutorialspoint.com" }
];
Adding the data
这里手动将一些数据添加到数据中等,如下所示 −
Here adding some data manually into the data as shown below −
function add() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "01", name: "prasad", age: 24, email: "prasad@tutorialspoint.com" });
request.onsuccess = function(event) {
alert("Prasad has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nPrasad is already exist in your database! ");
}
}
Retrieving Data
我们可以使用 get() 从数据库中检索数据
We can retrieve the data from the data base using with get()
function read() {
var transaction = db.transaction(["employee"]);
var objectStore = transaction.objectStore("employee");
var request = objectStore.get("00-03");
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
};
request.onsuccess = function(event) {
if(request.result) {
alert("Name: " + request.result.name + ", Age:
" + request.result.age + ", Email: " + request.result.email);
} else {
alert("Kenny couldn't be found in your database!");
}
};
}
使用 get(),我们可以将数据存储在对象中,而不是将数据存储在游标中,我们可以从游标中获取数据。
Using with get(), we can store the data in object instead of that we can store the data in cursor and we can retrieve the data from cursor.
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + " is " + cursor.value.name + ",
Age: " + cursor.value.age + ", Email: " + cursor.value.email);
cursor.continue();
} else {
alert("No more entries!");
}
};
}
Removing the data
我们可以通过 remove() 从 IndexedDB 中删除数据。以下是代码的样例
We can remove the data from IndexedDB with remove().Here is how the code looks like
function remove() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.delete("02");
request.onsuccess = function(event) {
alert("prasad entry has been removed from your database.");
};
}
HTML Code
为了显示所有数据,我们需要使用 onClick 事件,如下面的代码所示 −
To show all the data we need to use onClick event as shown below code −
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<title>IndexedDb Demo | onlyWebPro.com</title>
</head>
<body>
<button onclick = "read()">Read </button>
<button onclick = "readAll()"></button>
<button onclick = "add()"></button>
<button onclick = "remove()">Delete </button>
</body>
</html>
最终的代码应该是 −
The final code should be as −
<!DOCTYPE html>
<html>
<head>
<meta http-equiv = "Content-Type" content = "text/html; charset = utf-8" />
<script type = "text/javascript">
//prefixes of implementation that we want to test
window.indexedDB = window.indexedDB || window.mozIndexedDB ||
window.webkitIndexedDB || window.msIndexedDB;
//prefixes of window.IDB objects
window.IDBTransaction = window.IDBTransaction ||
window.webkitIDBTransaction || window.msIDBTransaction;
window.IDBKeyRange = window.IDBKeyRange || window.webkitIDBKeyRange ||
window.msIDBKeyRange
if (!window.indexedDB) {
window.alert("Your browser doesn't support a stable version of IndexedDB.")
}
const employeeData = [
{ id: "00-01", name: "gopal", age: 35, email: "gopal@tutorialspoint.com" },
{ id: "00-02", name: "prasad", age: 32, email: "prasad@tutorialspoint.com" }
];
var db;
var request = window.indexedDB.open("newDatabase", 1);
request.onerror = function(event) {
console.log("error: ");
};
request.onsuccess = function(event) {
db = request.result;
console.log("success: "+ db);
};
request.onupgradeneeded = function(event) {
var db = event.target.result;
var objectStore = db.createObjectStore("employee", {keyPath: "id"});
for (var i in employeeData) {
objectStore.add(employeeData[i]);
}
}
function read() {
var transaction = db.transaction(["employee"]);
var objectStore = transaction.objectStore("employee");
var request = objectStore.get("00-03");
request.onerror = function(event) {
alert("Unable to retrieve daa from database!");
};
request.onsuccess = function(event) {
// Do something with the request.result!
if(request.result) {
alert("Name: " + request.result.name + ",
Age: " + request.result.age + ", Email: " + request.result.email);
} else {
alert("Kenny couldn't be found in your database!");
}
};
}
function readAll() {
var objectStore = db.transaction("employee").objectStore("employee");
objectStore.openCursor().onsuccess = function(event) {
var cursor = event.target.result;
if (cursor) {
alert("Name for id " + cursor.key + " is " + cursor.value.name + ",
Age: " + cursor.value.age + ", Email: " + cursor.value.email);
cursor.continue();
} else {
alert("No more entries!");
}
};
}
function add() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.add({ id: "00-03", name: "Kenny", age: 19, email: "kenny@planet.org" });
request.onsuccess = function(event) {
alert("Kenny has been added to your database.");
};
request.onerror = function(event) {
alert("Unable to add data\r\nKenny is aready exist in your database! ");
}
}
function remove() {
var request = db.transaction(["employee"], "readwrite")
.objectStore("employee")
.delete("00-03");
request.onsuccess = function(event) {
alert("Kenny's entry has been removed from your database.");
};
}
</script>
</head>
<body>
<button onclick = "read()">Read </button>
<button onclick = "readAll()">Read all </button>
<button onclick = "add()">Add data </button>
<button onclick = "remove()">Delete data </button>
</body>
</html>
它将生成如下输出:
It will produce the following output −
HTML5 - Web messaging
网络消息是能够从服务器发送实时消息到客户端浏览器的功能。它在不同域、协议或端口中解决了跨域通信问题
Web messaging is the ability to send realtime messages from the server to the client browser. It overrides the cross domain communication problem in different domains, protocols or ports
例如,你想将页面中的数据发送到放置在 iframe 或语音邮件中的广告容器,在这种情况下,浏览器会抛出安全异常。使用网络消息,我们可以将数据作为消息事件传递。
For example, you want to send the data from your page to ad container which is placed at iframe or voice-versa, in this scenario, Browser throws a security exception. With web messaging we can pass the data across as a message event.
Message Event
消息事件触发了跨文档消息、频道消息、服务器发送的事件和网络套接字。它由消息事件接口描述。
Message events fires Cross-document messaging, channel messaging, server-sent events and web sockets.it has described by Message Event interface.
Attributes
Sr.No. |
Attributes & Description |
1 |
data Contains string data |
2 |
origin Contains Domain name and port |
3 |
lastEventId Contains unique identifier for the current message event. |
4 |
source Contains to A reference to the originating document’s window |
5 |
ports Contains the data which is sent by any message port |
Sending a cross-document message
在发送跨文档消息之前,我们需要创建一个新的网络浏览上下文,方法是创建新的 iframe 或新窗口。我们可以使用 postMessage() 发送数据,它有两个参数。它们如下 −
Before send cross document message, we need to create a new web browsing context either by creating new iframe or new window. We can send the data using with postMessage() and it has two arguments. They are as −
-
message − The message to send
-
targetOrigin − Origin name
Examples
从 iframe 向按钮发送消息
Sending message from iframe to button
var iframe = document.querySelector('iframe');
var button = document.querySelector('button');
var clickHandler = function() {
iframe.contentWindow.postMessage('The message to send.',
'https://www.tutorialspoint.com);
}
button.addEventListener('click',clickHandler,false);
在接收文档中接收跨文档消息
Receiving a cross-document message in the receiving document
var messageEventHandler = function(event){
// check that the origin is one we want.
if(event.origin == 'https://www.tutorialspoint.com') {
alert(event.data);
}
}
window.addEventListener('message', messageEventHandler,false);
Channel messaging
浏览上下文之间的双向通信称为通道消息传递。对于跨多个来源的通信,它非常有用。
Two-way communication between the browsing contexts is called channel messaging. It is useful for communication across multiple origins.
The MessageChannel and MessagePort Objects
创建消息通道时,它内部创建两个端口来发送数据并转发到另一浏览上下文。
While creating messageChannel, it internally creates two ports to sending the data and forwarded to another browsing context.
-
postMessage() − Post the message throw channel
-
start() − It sends the data
-
close() − It close the ports
在这个场景中,我们正在从一个 iframe 向另一个 iframe 发送数据。这里我们在函数中调用数据并将数据传递给 DOM。
In this scenario, we are sending the data from one iframe to another iframe. Here we are invoking the data in function and passing the data to DOM.
var loadHandler = function() {
var mc, portMessageHandler;
mc = new MessageChannel();
window.parent.postMessage('documentAHasLoaded','http://foo.example',[mc.port2]);
portMessageHandler = function(portMsgEvent) {
alert( portMsgEvent.data );
}
mc.port1.addEventListener('message', portMessageHandler, false);
mc.port1.start();
}
window.addEventListener('DOMContentLoaded', loadHandler, false);
在上述代码中,它从端口 2 获取数据,现在它将数据传递给第二个 iframe
Above code, it is taking the data from port 2, now it will pass the data to second iframe
var loadHandler = function() {
var iframes, messageHandler;
iframes = window.frames;
messageHandler = function(messageEvent) {
if( messageEvent.ports.length > 0 ) {
// transfer the port to iframe[1]
iframes[1].postMessage('portopen','http://foo.example',messageEvent.ports);
}
}
window.addEventListener('message',messageHandler,false);
}
window.addEventListener('DOMContentLoaded',loadHandler,false);
现在,第二个文档使用 portMsgHandler 函数处理数据。
Now second document handles the data by using the portMsgHandler function.
var loadHandler() {
// Define our message handler function
var messageHandler = function(messageEvent) {
// Our form submission handler
var formHandler = function() {
var msg = 'add <foo@example.com> to game circle.';
messageEvent.ports[0].postMessage(msg);
}
document.forms[0].addEventListener('submit',formHandler,false);
}
window.addEventListener('message',messageHandler,false);
}
window.addEventListener('DOMContentLoaded',loadHandler,false);
HTML5 - CORS
Cross-origin resource sharing (CORS) 是一个允许来自网络浏览器中其他域的受限制资源的机制。
Cross-origin resource sharing (CORS) is a mechanism to allows the restricted resources from another domain in web browser.
比如,如果我们在 html5 示例部分中点击 HTLM5 视频播放器。它会请求相机权限。如果用户允许该权限,它才会打开相机,否则它将不会为网络应用程序打开相机。
For suppose, if you click on HTML5- video player in html5 demo sections. it will ask camera permission. if user allow the permission then only it will open the camera or else it doesn’t open the camera for web applications.
Making a CORS request
在这里,Chrome、Firefox、Opera 和 Safari 都使用 XMLHttprequest2 对象,而 Internet Explorer 使用类似的 XDomainRequest 对象。
Here Chrome, Firefox, Opera and Safari all use the XMLHttprequest2 object and Internet Explorer uses the similar XDomainRequest object, object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// Check if the XMLHttpRequest object has a "withCredentials" property.
// "withCredentials" only exists on XMLHTTPRequest2 objects.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// Otherwise, check if XDomainRequest.
// XDomainRequest only exists in IE, and is IE's way of making CORS requests.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// Otherwise, CORS is not supported by the browser.
xhr = null;
}
return xhr;
}
var xhr = createCORSRequest('GET', url);
if (!xhr) {
throw new Error('CORS not supported');
}
Event handles in CORS
Sr.No. |
Event Handler & Description |
1 |
onloadstart Starts the request |
2 |
onprogress Loads the data and send the data |
3 |
onabort Abort the request |
4 |
onerror request has failed |
5 |
onload request load successfully |
6 |
ontimeout time out has happened before request could complete |
7 |
onloadend When the request is complete either successful or failure |
Example of onload or onerror event
xhr.onload = function() {
var responseText = xhr.responseText;
// process the response.
console.log(responseText);
};
xhr.onerror = function() {
console.log('There was an error!');
};
Example of CORS with handler
下面的示例将显示 makeCorsRequest() 和 onload 处理程序的示例
Below example will show the example of makeCorsRequest() and onload handler
// Create the XHR object.
function createCORSRequest(method, url) {
var xhr = new XMLHttpRequest();
if ("withCredentials" in xhr) {
// XHR for Chrome/Firefox/Opera/Safari.
xhr.open(method, url, true);
} else if (typeof XDomainRequest != "undefined") {
// XDomainRequest for IE.
xhr = new XDomainRequest();
xhr.open(method, url);
} else {
// CORS not supported.
xhr = null;
}
return xhr;
}
// Helper method to parse the title tag from the response.
function getTitle(text) {
return text.match('<title>(.*)?</title>')[1];
}
// Make the actual CORS request.
function makeCorsRequest() {
// All HTML5 Rocks properties support CORS.
var url = 'http://www.tutorialspoint.com';
var xhr = createCORSRequest('GET', url);
if (!xhr) {
alert('CORS not supported');
return;
}
// Response handlers.
xhr.onload = function() {
var text = xhr.responseText;
var title = getTitle(text);
alert('Response from CORS request to ' + url + ': ' + title);
};
xhr.onerror = function() {
alert('Woops, there was an error making the request.');
};
xhr.send();
}
HTML5 - Web RTC
Web RTC 由万维网联盟 (W3C) 引入。它支持用于语音呼叫、视频聊天和 P2P 文件共享的浏览器到浏览器的应用程序。
Web RTC introduced by World Wide Web Consortium (W3C). That supports browser-tobrowser applications for voice calling, video chat, and P2P file sharing.
如果你想尝试一下?Web RTC 可用于 Chrome、Opera 和 Firefox。Web RTC 实现了三个 API,如下所示 −
If you want to try out? web RTC available for Chrome, Opera, and Firefox. Web RTC implements three API’s as shown below −
-
MediaStream − get access to the user’s camera and microphone.
-
RTCPeerConnection − get access to audio or video calling facility.
-
RTCDataChannel − get access to peer-to-peer communication.
MediaStream
MediaStream 表示同步的媒体流,例如,点击 HTML5 示例部分中的 HTML5 视频播放器,或者点击 here 。
The MediaStream represents synchronized streams of media, For an example, Click on HTML5 Video player in HTML5 demo section or else click here.
上述示例包含 stream.getAudioTracks() 和 stream.VideoTracks()。如果没有音轨,它将返回一个空数组,它将检查视频流,如果网络摄像头已连接,stream.getVideoTracks() 将返回一个 MediaStreamTrack 数组,表示网络摄像头的流。一个简单的示例是聊天应用程序,聊天应用程序从网络摄像头、后置摄像头、麦克风获取流。
The above example contains stream.getAudioTracks() and stream.VideoTracks(). If there is no audio tracks, it returns an empty array and it will check video stream,if webcam connected, stream.getVideoTracks() returns an array of one MediaStreamTrack representing the stream from the webcam. A simple example is chat applications, a chat application gets stream from web camera, rear camera, microphone.
Sample code of MediaStream
function gotStream(stream) {
window.AudioContext = window.AudioContext || window.webkitAudioContext;
var audioContext = new AudioContext();
// Create an AudioNode from the stream
var mediaStreamSource = audioContext.createMediaStreamSource(stream);
// Connect it to destination to hear yourself
// or any other node for processing!
mediaStreamSource.connect(audioContext.destination);
}
navigator.getUserMedia({audio:true}, gotStream);
Screen capture
它也可以在具有 mediaStreamSource 的 Chrome 浏览器中,并且它需要 HTTPS。此功能尚未在 Opera 中提供。
It’s also possible in Chrome browser with mediaStreamSource and it requires HTTPS. This feature is not yet available in opera.
Session Control, Network & Media Information
Web RTC 需要浏览器之间的点对点通信。此机制需要信令、网络信息、会话控制和媒体信息。Web 开发人员可以选择不同的机制在浏览器之间进行通信,例如 SIP 或 XMPP 或任何双向通信。
Web RTC required peer-to-peer communication between browsers. This mechanism required signaling, network information, session control and media information. Web developers can choose different mechanism to communicate between the browsers such as SIP or XMPP or any two way communications.
Sample code of createSignalingChannel()
var signalingChannel = createSignalingChannel();
var pc;
var configuration = ...;
// run start(true) to initiate a call
function start(isCaller) {
pc = new RTCPeerConnection(configuration);
// send any ice candidates to the other peer
pc.onicecandidate = function (evt) {
signalingChannel.send(JSON.stringify({ "candidate": evt.candidate }));
};
// once remote stream arrives, show it in the remote video element
pc.onaddstream = function (evt) {
remoteView.src = URL.createObjectURL(evt.stream);
};
// get the local stream, show it in the local video element and send it
navigator.getUserMedia({ "audio": true, "video": true }, function (stream) {
selfView.src = URL.createObjectURL(stream);
pc.addStream(stream);
if (isCaller)
pc.createOffer(gotDescription);
else
pc.createAnswer(pc.remoteDescription, gotDescription);
function gotDescription(desc) {
pc.setLocalDescription(desc);
signalingChannel.send(JSON.stringify({ "sdp": desc }));
}
});
}
signalingChannel.onmessage = function (evt) {
if (!pc)
start(false);
var signal = JSON.parse(evt.data);
if (signal.sdp)
pc.setRemoteDescription(new RTCSessionDescription(signal.sdp));
else
pc.addIceCandidate(new RTCIceCandidate(signal.candidate));
};