directory

 

  • HTML tutorial
  • HTML5 browser support
  • HTML 5 new elements
  • HTML5 Semantic Elements
  • HTML5 code specification
  • HTML5 MathML
  • HTML5 Web SQL database
  • HTML 5 migration
  • HTML5 Canvas
  • HTML 5 inline SVG
  • HTML5 Canvas VS svg
  • HTML 5 multimedia
  • HTML 5 Object element
  • HTML 5 Audio Audio
  • HTML 5 Video Video
  • HTML5’s new input type
  • HTML5 form Elements
  • HTML5 Form Attributes
  • HTML5 Geolocation
  • HTML 5 drag and drop
  • HTML 5 Web store
  • HTML5 application caching
  • HTML5 websocket
  • The HTML5 server sends events

 

 

HTML tutorial

HTML5 is the latest revision of HTML, finalized by the World Wide Web Consortium (W3C) in October 2014.

HTML5 is designed to support multimedia on mobile devices.

HTML5 is easy to learn.

 

What is it?

HTML5 is the latest HTML standard.

HTML5 is specifically designed to host rich Web content without the need for additional plug-ins.

HTML5 has new semantic, graphical, and multimedia elements.

HTML5 provides new elements and new apis that simplify building Web applications.

HTML5 is cross-platform and is designed to run on different types of hardware (PCS, tablets, phones, TVS, and so on).

 

Some interesting new features in HTML5:

  • Canvas element for drawing
  • Video and audio elements for media playback
  • Better support for local offline storage
  • New special content elements such as article, footer, header, nav, section
  • New form controls such as Calendar, Date, Time, email, URL, and Search

The declaration must be in the first line of the HTML5 document and is very simple to use:

<! Doctypehtml>
Copy the code
<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
<body>

<p>Sun's CSDN blog</p>

</body>
</html>
Copy the code

The improvement of HTML 5

  • The new element
  • New properties
  • Full support for CSS3
  • Video and Audio
  • 2 d / 3 d drawings
  • The local store
  • Local SQL data
  • The Web application

Html4 multimedia

Using HTML5, you can easily play video and audio on a web page.

  • HTML5 video
  • HTML5 audio

HTML 5 application

Using HTML5 you can easily develop applications

  • Local data store
  • Accessing local Files
  • Local SQL data
  • Cache references
  • Javascript workers
  • XHTMLHttpRequest 2

Using HTML5 you can simply draw graphics:

  • Use the Canvas element.
  • Use inline SVG.
  • Use CSS3 2D conversion, CSS3 3D conversion.

It use CSS 3

  • The new selector
  • New properties
  • animation
  • 2 d / 3 d conversion
  • Rounded corners
  • shadows
  • Downloadable fonts

Semantic elements

The latest versions of Safari, Chrome, Firefox, and Opera support some HTML5 features. Internet Explorer 9 will support certain HTML5 features.

The following versions of IE9 browsers are compatible with HTML5 methods, using the HTML5shiv package:

<! --[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/r29/html5.js"></script> <! [endif]-->
Copy the code

After loading, initialize the CSS for the new tag:

/*html5*/
article,aside,dialog,footer,header,section,nav,figure,menu{display:block}
Copy the code

 

HTML5 browser support

Major browsers now support HTML5, but some older Internet Explorer doesn’t.

You can get some older browsers (which don’t support HTML5) to support HTML5.

 

HTML5 defines eight new SEMANTIC HTML elements. All of these elements are block-level elements.

To enable older browsers to display these elements correctly, you can set the CSS display property to block:

header, section, footer, aside, nav, main, article, figure {
    display: block; 
}
Copy the code

You can add new elements to the HTML.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sun calls beast to add new elements to HTML</title>
    <script>
        document.createElement("myFan")
    </script>
    <style>
        myFan {
            background-color: green;
            padding: 50px;
            display: block;
            font-size: 50px;
        }
    </style>
</head>
<body>

<p>Sun's CSDN blog</p>

</body>
</html>
Copy the code

We can use “HTML5 Enabling JavaScript”, “SHIv”, created by Sjoerd Visscher, to address Internet Explorer.

Html5shiv is a better solution for IE browser. Html5shiv mainly solves the problem that the new elements proposed by HTML5 are not recognized by IE6-8. These new elements cannot be wrapped as parent elements and cannot apply CSS styles.

<! DOCTYPEhtml>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Sun calls beast to solve IE browser</title>
    
    <! --[if lt IE 9]> <script src="https://cdn.bootcss.com/html5shiv/r29/html5.js"></script> <! [endif]-->
    
</head>
<body>

<p>Sun's CSDN blog</p>

</body>
</html>
Copy the code

The html5shiv.js reference code must be placed in the element because Internet Explorer needs to load the file before parsing new HTML5 elements.

 

HTML 5 new elements

HTML4 has changed a lot since 1999. Today, several elements in HTML4 have been discarded, and these elements have been removed or redefined in HTML5.

To better handle today’s Web applications, HTML5 has added many new elements and features, such as: drawing graphics, multimedia content, better page structure, better form handling, and several apis for drag-and-drop elements, positioning, including Web application caching, storage, web workers, etc

The canvas element

New media elements

New form element

 

HTML5 Semantic Elements

A semantic element clearly describes its meaning to the browser and the developer.

Examples of non-semantic elements:

and
– regardless of content.

Semantic element instances:

,

, and – clearly define its contents.

 

Many existing web sites contain HTML code:

<header>
<nav>
<section>
<article>
<aside>
<figcaption>
<figure>
<footer>
Copy the code

The

tag defines sections (sections, extents) in the document. Such as a chapter, header, footer, or other part of a document.

According to the W3C HTML5 document: a section contains a set of content and its title.

<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8"> 
    <title>Sun Called beast's blog</title>
</head>
<body>
<section>
    <h1>This is Sun's blog</h1>
    <p>This is the section of the test section</p>
</section>

</body>
</html>
Copy the code

The

tag defines individual content. .

Example of the

element:

  • Forum post
  • Blog post
  • News story
  • Comment
<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
<body>
<article>
    <h1>This is Sun's blog</h1>
    <p>This is the test article paragraph</p>
</article>

</body>
</html>
Copy the code

 

The

The

<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
<body>
<nav>
    <a href="/html">html</a>
    <a href="/css">css</a>
    <a href="/html5">html5</a>
    <a href="/javaScript">javaScript</a>
</nav>

</body>
</html>
Copy the code

The

The content of the aside label should be related to the content of the main area.

<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
<body>
<p>These are all sun's fans</p>
<aside>
    <h2>Sun Is a fan of The beast</h2>
    <p>Sun Called beast fan books</p>
</aside>
</body>
</html>
Copy the code

The

element describes the header area of the document

The

element is used to define the presentation area of the content.

You can use more than one

element in a page.

<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
<body>
<article>
    <p>These are all sun's fans</p>
    <header>
        <h2>Sun Is a fan of The beast</h2>
        <p>Sun Called beast fan books</p>
    </header>
</article>

</body>
</html>
Copy the code

The

element describes the bottom area of the document.

The

element should contain its inclusion element

A footer usually contains the author of the document, copyright information, terms of use for the link, contact information, etc

You can use more than one

element in a document.

<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
<body>
<footer>
    <p>Copyright: Sun Xiaoshou</p>
    <p><time>2020/6/18</time></p>
</footer>

</body>
</html>
Copy the code

The

tag specifies individual stream content (images, charts, photos, code, and so on).

The content of the

element should be related to the main content, but it should not affect the document flow if it is removed.

The

tag defines the title of the

element.

Elements should be placed in the position of the first or last child of the “figure” element.

<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
<body>
<figure>
    <p>Sun's fans came to pay attention</p>
    <figcaption>The behavior of fans</figcaption>
</figure>

</body>
</html>
Copy the code

 

HTML5 code specification

Many Web developers know little about the HTML code specification.

Between 2000 and 2010, many Web developers made the switch from HTML to XHTML.

Developers working with XHTML have developed better HTML writing specifications.

For HTML5, we should form a good code specification, the following provides several suggestions for specification.

 

HTML5 element names can use both upper and lower case letters.

Lower case letters are recommended:

  • A mixed style of upper and lower case is very bad.
  • Developers typically use lowercase (like XHTML).
  • The lowercase style is more refreshing.
  • Lowercase letters are easy to write.

 

In HTML5, you don’t have to turn everything off (e.g

Element), but we recommend adding a close tag to each element.

<p></p>
Copy the code

In HTML5, empty HTML elements don’t have to be closed either:

<br>
Copy the code

A slash (/) is required in XHTML and XML.

This style is great if you expect XML software to use your pages.

 

HTML5 attribute names allow upper and lower case letters.

We recommend using lower-case attribute names:

  • It is a very bad habit to use both case and case.
  • Developers typically use lowercase (like XHTML).
  • The lowercase style is more refreshing.
  • Lowercase letters are easy to write.
<h1 id="manu"></h1>
Copy the code

HTML5 attribute values can be done without quotes.

Attribute values we recommend using quotes:

  • Use quotation marks if attribute values contain Spaces.
  • If mixed style is not recommended, unified style is recommended.
  • Attribute values are easy to read using quotation marks.
<form class="stire mmm">
Copy the code

Images usually use the Alt attribute. It can replace the picture display when the picture cannot be displayed.

<img src="html5.jpe" alt="html5" style="width:50px; height:50px">
Copy the code

Define the size of the image so that it can be loaded with a designated space to reduce flickering.

 

Spaces can be used before and after an equal sign. It is recommended to use fewer Spaces

<meta charset="UTF-8">
Copy the code

 

Scrolling code left and right is inconvenient with an HTML editor.

Each line of code should contain at least 80 characters.

 

Don’t add blank lines for no reason.

Add blank lines for each logical function block to make it easier to read.

Indent with two Spaces. TAB is not recommended.

Don’t use unnecessary blank lines and indentation in short code.

 

<! DOCTYPEhtml>
<html lang="en">
<head>
   <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
<body>
<figure>
    <p>Sun's fans came to pay attention</p>
    <figcaption>The behavior of fans</figcaption>
</figure>

</body>
</html>
Copy the code

In standard HTML5, the < HTML > and < body> tags can be omitted.

<! DOCTYPEhtml>
<head>
   <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
</head>
    <p>Sun's fans came to pay attention</p>
Copy the code

The element is the root element of the document that describes the language of the page:

<! DOCTYPEhtml>
<html lang="En">
</html>
Copy the code

The declarative language is intended to be convenient for screen readers and search engines.

Omitting < HTML > or crashes in DOM and XML software.

Omitting causes an error in older browsers (IE9).

 

In HTML5, the

element is required. The title name describes the topic of the page. The title and language can help search engines quickly understand the topic of your page:

<! DOCTYPEhtml>
<html lang="En">
<head>
    <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>   
</head>
<body>
<h1>This is a headline</h1>
<p>This is a paragraph</p>
</body>
</html>
Copy the code

Comments can be written in
:

<! -- This is the comment content -->
Copy the code

The stylesheet uses a concise syntax format (the type attribute is not required):

<link rel="stylesheet" href="my.css">
Copy the code
<! DOCTYPEhtml>
<html lang="En">
<head>
    <meta charset="UTF-8">
    <title>Sun Called beast's blog</title>
    <link rel="stylesheet" href="my.css">
    <style>
        body{
            background-color: green;
            font-size: 15px;
            height: 50px;
            width: 15px;
        }
        
    </style>
   
</head>
<body>
<h1>This is a headline</h1>
<p>This is a paragraph</p>
</body>
</html>
Copy the code

A long rule can be written as multiple lines:

  • Put the open curly brace on the same line as the selector.
  • Add a space between the open curly brace and the selector.
  • Use two Spaces to indent.
  • Add a space between the colon and the attribute value.
  • Use a space after commas and symbols.
  • Use a semicolon at the end of each attribute and value.
  • Use quotation marks only if the attribute value contains Spaces.
  • The closing curly brace is placed on the new line.
  • Each line contains a maximum of 80 characters.

 

Use concise syntax to load external script files (the type attribute is not required):

<script src="my.js"></script>
Copy the code

 

Most Web servers (Apache, Unix) are case-sensitive: london.jpg cannot be accessed through London.jpg.

Other Web servers (Microsoft, IIS) are case insensitive: London.jpg can be accessed via London.jpg or London.jpg.

You must maintain a uniform style, and we recommend using lowercase file names.

 

HTML files can be postfixed with.html (or.htm).

The CSS file extension is.css.

JavaScript files have a.js suffix.

 

If the server has only “index.html” configured as the default file, you must name the file “index.html”, not “index.htm”.

However, usually the server can set more than one default file, and you can set the default file name as needed.

 

HTML5 MathML

HTML5 can use MathML elements in documents with tags like
… < / math >.

MathML is a mathematical markup language, a standard based on XML (a subset of the Standard Common Markup Language) for writing mathematical symbols and formulas on the Internet.

<! DOCTYPEhtml>
<html>
   <head>
      <meta charset="UTF-8">
      <title>Sun Called beast's blog</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>aaa
   </body>
</html> 
Copy the code

A 2 by 2 matrix

 

HTML5 Web SQL database

The Web SQL database API is not part of the HTML5 specification, but it is a separate specification that introduces a set of APIs for manipulating client databases using SQL.

If you are a Web backend programmer, it should be easy to understand SQL operations.

 

Here are the three core methods defined in the specification:

  1. OpenDatabase: This method creates a database object using an existing database or a new database.
  2. Transaction: This method allows us to control a transaction and perform a commit or rollback based on that situation.
  3. ExecuteSql: This method is used to execute actual SQL queries.

We can use the openDatabase() method to open an existing database, or create a new one if it doesn’t exist, using the following code:

Var db = openDatabase('mydb', '1.0', 'Test db', 2 \* 1024 \* 1024);Copy the code

The openDatabase() method has five parameters:

  1. Database name
  2. The version number
  3. Describe the text
  4. Database size
  5. Create a callback

The fifth parameter, the create callback, is called after the database is created.

 

Perform the operation using database.transaction() :

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)'); });Copy the code

The above statement will create a table named LOG in the ‘myDB’ database.

 

After executing the create table statement above, we can insert some data:

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)'); ExecuteSql ('INSERT INTO LOGS (id, log) VALUES (1, ') '); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "http://bensonsun.piworker.com/?code=BensonSun")'); });Copy the code

Dynamic values to insert data:

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]); });Copy the code

E_id and e_log in the instance are external variables, and executeSql maps each entry in the array parameters to the “? “.

 

Read data that already exists in the database:

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)'); ExecuteSql ('INSERT INTO LOGS (id, log) VALUES (1, "log ")); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "http://bensonsun.piworker.com/?code=BensonSun")'); }); db.transaction(function (tx) { tx.executeSql('SELECT * FROM LOGS', [], function (tx, results) { var len = results.rows.length, i; MSG = "<p> <p> "; document.querySelector('#status').innerHTML += msg; for (i = 0; i < len; i++){ alert(results.rows.item(i).log ); } }, null); });Copy the code

Complete example:

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)'); ExecuteSql ('INSERT INTO LOGS (id, log) VALUES (1, "log ")); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "http://bensonsun.piworker.com/?code=BensonSun")'); msg = '<p>The data table has been created with two data inserts.</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>Query record number: "+ 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);
});
Copy the code

Delete records using the following format:

db.transaction(function (tx) {
    tx.executeSql('DELETE FROM LOGS  WHERE id=1');
});
Copy the code

Delete specified data id can also be dynamic:? Represents a placeholder

db.transaction(function(tx) { tx.executeSql('DELETE FROM LOGS WHERE id=? ', [id]); });Copy the code

Update records use the following format:

db.transaction(function (tx) {
    tx.executeSql('UPDATE LOGS SET log='http://bensonsun.piworker.com/?code=BensonSun' WHERE id=2');
});
Copy the code

Dynamically updates the specified data ID

db.transaction(function(tx) {
    tx.executeSql('UPDATE LOGS SET log='www.axihe.com' WHERE id=?', [id]);
});
Copy the code

Complete example:

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)'); ExecuteSql ('INSERT INTO LOGS (id, log) VALUES (1, "log ")); tx.executeSql('INSERT INTO LOGS (id, log) VALUES (2, "http://bensonsun.piworker.com/?code=BensonSun")'); MSG = '<p> Data table created and inserted two data. </p>'; document.querySelector('#status').innerHTML = msg; }); db.transaction(function (tx) { tx.executeSql('DELETE FROM LOGS WHERE id=1'); MSG = '<p> Delete record 1. </p>'; document.querySelector('#status').innerHTML = msg; }); db.transaction(function (tx) { tx.executeSql('UPDATE LOGS SET log='http://bensonsun.piworker.com/?code=BensonSun' WHERE id=2'); MSG = '<p> Update the record with id 2. </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> <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); });Copy the code

 

HTML5 Web Worker

Web workers are JavaScript that runs in the background and does not affect page performance.

 

When a script is executed in an HTML page, the state of the page is unresponsive until the script is complete.

Web workers are JavaScript running in the background, independent of other scripts, and do not affect page performance. You can continue to do whatever you want: click, select content, and so on, while the Web worker runs in the background.

 

Web Workers is supported in Internet Explorer 10, Firefox, Chrome, Safari, and Opera.

<div class="example_code" style="background-color: rgb(238, 238, 238);">Count:<output id="result">0</output>
    <p>
        <button onclick="startWorker()">Start the Worker</button> 
        <button onclick="stopWorker()">Stop the Worker</button>
        <br>
        <br>
    </p>
    <script>
        var w;
        function startWorker(){
            if(typeof(Worker)! = ="undefined") {if(typeof(w)=="undefined"){
                    w=new Worker("demo_workers.js");
                }
                w.onmessage = function (event) {
                    document.getElementById("result").innerHTML=event.data;
                };
            } else {
                document.getElementById("result").innerHTML
                    ="Sorry your browser does not support Web Workers..."; }}function stopWorker(){ 
            w.terminate();
            w = undefined;
        }
    </script>
</div>
Copy the code

Example:

var i=0;
function timedCount() {
    i=i+1;
    postMessage(i);
    setTimeout("timedCount()".500);
}
timedCount();
Copy the code

Now that we have the Web worker file, we need to invoke it from the HTML page.

The following code checks to see if the worker exists, and if not – it creates a new Web worker object and runs the code in “demo_workers.js” :

if(typeof(w)=="undefined"){
    w=new Worker("demo_workers.js");
}
Copy the code

We can then generate and receive messages from the Web worker.

Add an “onMessage” event listener to the Web worker:

w.onmessage=function(event){
    document.getElementById("result").innerHTML=event.data;
};
Copy the code

When we create the Web Worker object, it continues to listen for messages (even after the external script completes) until it is terminated.

To terminate the Web worker and release browser/computer resources, use the terminate() method:

w.terminate();
Copy the code

Complete example:

<! DOCTYPEhtml>
<html>
<head> 
<meta charset="utf-8"> 
<title>Assi River Tutorial (Axihe.com)</title> 
</head>
<body>
 
<p>Count:<output id="result"></output></p>
<button onclick="startWorker()">Start to work</button> 
<button onclick="stopWorker()">Stop working</button>
 
<p><strong>Note:</strong>Internet Explorer 9 and earlier Versions of Internet Explorer do not support Web Workers.</p>
 
<script>
var w;
 
function startWorker() {
    if(typeof(Worker) ! = ="undefined") {
        if(typeof(w) == "undefined") {
            w = new Worker("demo_workers.js");
        }
        w.onmessage = function(event) {
            document.getElementById("result").innerHTML = event.data;
        };
    } else {
        document.getElementById("result").innerHTML = "Sorry your browser does not support Web Workers..."; }}function stopWorker(){ 
    w.terminate();
    w = undefined;
}
</script>
 
</body>
</html>
Copy the code

Because Web workers are in external files, they cannot access the following JavaScript objects:

  • The window object
  • The document object
  • The parent object

 

TML5 migration

A typical html4

<! DOCTYPEHTML PUBLIC "-//W3C//DTD HTML4 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
<html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>HTML4</title>
<style>
  body {font-family:Verdana,sans-serif;font-size:0.8 em; }div#header.div#footer.div#content.div#post 
  {border:1px solid grey;margin:5px;margin-bottom:15px;padding:8px;background-color:white; }div#header.div#footer {color:white;background-color:# 444;margin-bottom:5px; }div#content {background-color:#ddd; }div#menu ul {margin:0;padding:0; }div#menu ul li {display:inline; margin:5px; }</style>
</head>
<body>
<div id="header">
  <h1>Monday Times</h1>
</div>
<div id="menu">
  <ul>
    <li>News</li>
    <li>Sports</li>
    <li>Weather</li>
  </ul>
</div>
<div id="content">
<h2>News Section</h2>
<div id="post">
  <h2>News Article</h2>
  <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum 
  lurum hurum turum.</p>
  <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum 
  lurum hurum turum.</p>
</div>
<div id="post">
  <h2>News Article</h2>
  <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum 
  lurum hurum turum.</p>
  <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum 
  lurum hurum turum.</p>
</div>
</div>
<div id="footer">
  <p>&copy; 2014 Monday Times. All rights reserved.</p>
</div>
</body>
</html>
Copy the code

HTML4 doctype:

<! DOCTYPEHTML PUBLIC "-//W3C//DTD HTML4 Transitional//EN" 
"http://www.w3.org/TR/html4/loose.dtd">
Copy the code

HTML 5 doctype:

<! DOCTYPEhtml>
Copy the code

Encoding type HTML4:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
Copy the code

Encoding type HTML5:

<meta charset="utf-8">
Copy the code

All modern browsers support HTML5 semantic elements.

In addition, you can “teach” older browsers how to handle “unknown elements.”

Shivs added for Internet Explorer support:

<! --[if lt IE 9]> <script src="http://html5shiv.googlecode.com/svn/trunk/html5.js"></script> <! [endif]-->Copy the code

HTML5 semantic elements add CSS

div#header.div#footer.div#content.div#post {
    border:1px solid grey;margin:5px;margin-bottom:15px;padding:8px;background-color:white;
}
div#header.div#footer {
    color:white;background-color:# 444;margin-bottom:5px;
}
div#content {
    background-color:#ddd;
}
div#menu ul {
    margin:0;padding:0;
}
div#menu ul li {
    display:inline; margin:5px;
}
Duplicate with equal CSS styles for HTML5 semantic elements:
header,footer,section,article {
    border:1px solid grey;margin:5px;margin-bottom:15px;padding:8px;background-color:white;
}
header.footer {
    color:white;background-color:# 444;margin-bottom:5px;
}
section {
    background-color:#ddd;
}
nav ul  {
    margin:0;padding:0;
}
nav ul li {
    display:inline; margin:5px;
}
Copy the code

 

Add id= “header” and id= “footer” to the

element:
<div id="header">
  <h1>Monday Times</h1>
</div>.<div id="footer">
  <p>&copy; 2014 W3Schools. All rights reserved.</p>
</div>
Copy the code
<header>
  <h1>Monday Times</h1>
</header>.<footer>
  <p>© 2014 W3Schools. All rights reserved.</p>
</footer>
Copy the code

Change the

element id= “menu” to the HTML5 semantic element

<div id="menu">
  <ul>
    <li>News</li>
    <li>Sports</a></li>
    <li>Weather</li>
  </ul>
</div>
Copy the code
<nav>
  <ul>
    <li>News</li>
    <li>Sports</a></li>
    <li>Weather</li>
  </ul>
</nav>
Copy the code

Change the element id= “content” to the HTML5 semantic element <section> :

<div id="content">.</div>
Copy the code
<section>.</section>
Copy the code

Change all

elements of class= “post” to HTML5 semantic elements:
<div class="post">
  <h2>News Article</h2>
  <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum 
  lurum hurum turum.</p>
</div>
Copy the code
<article>
  <h2>News Article</h2>
  <p>Ipsum lurum hurum turum ipsum lurum hurum turum ipsum lurum hurum turum ipsum 
  lurum hurum turum.</p>
</article>
Copy the code

In the HTML5 standard, the difference between

and

is confusingly small.

In the HTML5 standard,

elements are positioned as blocks of related elements.

The

element is defined as a complete self-contained block of related elements.

The

element is defined as a block of child elements.

How do you understand that?

In the example above, we used

as a container for the related
.

However, we can also use

as a container for articles.

<article>In the<section>In the<div>:<article>
<section>
<h2>Famous Cities</h2>
<div class="city">
<h2>London</h2>
<p>London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.</p>
</div>
<div class="city">
<h2>Paris</h2>
<p>Paris is the capital and most populous city of France.</p>
</div>
<div class="city">
<h2>Tokyo</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p>
</div>
</section>
<section>
<h2>Famous Countries</h2>
<div class="country">
<h2>England</h2>
<p>London is the capital city of England. It is the most populous city in the United Kingdom,
with a metropolitan area of over 13 million inhabitants.</p>
</div>
<div class="country">
<h2>France</h2>
<p>Paris is the capital and most populous city of France.</p>
</div>
<div class="country">
<h2>Japan</h2>
<p>Tokyo is the capital of Japan, the center of the Greater Tokyo Area,
and the most populous metropolitan area in the world.</p>
</div>
</section>
</article>
Copy the code

 

HTML5 Canvas

The

tag defines graphics, such as charts and other images, which you must draw using scripts.

Draw a red rectangle, gradient rectangle, colored rectangle, and some colored text on the Canvas.

 

The HTML5 Canvas element is used for drawing graphics, which is done by scripting (usually JavaScript).

The Canvas tag is just a container for graphics, and you must use scripts to draw graphics.

You can use canvas to draw paths, boxes, circles, characters, and add images in a variety of ways.

 

Browser support:

The numbers in the table indicate support

The first browser version number of the element

 

A canvas in a web page is a rectangular box drawn by the Canvas element.

Note: By default

The element has no borders and no content.

<canvas id="myCanvas" style="height: 200px; width: 200px;"></canvas>
Copy the code

Use the style attribute to add borders:

<canvas id="myCanvas" width="200" height="100"
    style="border:1px solid #000000;">
</canvas>
Copy the code

 

The Canvas element itself has no drawing capability. All the drawing must be done inside JavaScript:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.fillStyle="#FF0000";
ctx.fillRect(0.0.150.75);
Copy the code

Example:

var c=document.getElementById("myCanvas");
Copy the code

Then, create the context object:

var ctx=c.getContext("2d");
Copy the code

The getContext(” 2D “) object is a built-in HTML5 object with multiple methods for drawing paths, rectangles, circles, characters, and adding images.

The following two lines draw a red rectangle:

Draw a red rectangle:

ctx.fillStyle="#FF0000";  
ctx.fillRect(0.0.150.75);
Copy the code

 

Set the fillStyle property to a CSS color, gradient, or pattern. FillStyle defaults to #000000 (black).

The fillRect(_x,y,width,height_) methods define how the rectangle is currently filled.

Coordinates:

Canvas is a two-dimensional grid.

The top left corner of the canvas is (0,0)

The fillRect method above has arguments (0,0,150,75).

Meaning: draw a rectangle of 150×75 on the canvas, starting at the top left corner (0,0).

Path:

To draw lines on the Canvas, we will use the following two methods:

  • moveTo(x,yDefine the line start coordinates
  • lineTo(x,yDefine line end coordinates

To draw lines we must use the “ink” method, like stroke().

Example: define the start coordinates (0,0), and the end coordinates (200,100). Then use the stroke() method to draw the line:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.moveTo(0.0);
ctx.lineTo(200.100);
ctx.stroke();
Copy the code

Draw a circle on the canvas

arc(x,y,r,start,stop)
Copy the code

We actually use “ink” methods for drawing circles, such as stroke() or fill().

Example: Draw a circle using the Arc () method:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.beginPath();
ctx.arc(95.50.40.0.2*Math.PI);
ctx.stroke();
Copy the code

The text

Using Canvas to draw text, the important properties and methods are as follows:

  • Font – Defines the font
  • fillText(text,x,y) – Draws solid text on canvas
  • strokeText(text,x,y) – Draws hollow text on canvas

Use the fillText () :

Example: Use “Arial” font to draw a 30px high text (solid) on the canvas:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.fillText("Hello World".10.50);
Copy the code

Use the strokeText () :

Example: Use Arial font to draw a 30px high text (hollow) on the canvas:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.strokeText("Hello World".10.50);
Copy the code

The gradient

Gradients can be filled in rectangles, circles, lines, text, etc. Various shapes can define their own different colors.

There are two different ways to set the Canvas gradient:

  • createLinearGradient(x,y,x1,y1) – Create a line gradient
  • createRadialGradient(x,y,r,x1,y1,r1) – Create a radial/circular gradient

When we use gradient objects, we must use two or more stop colors.

The addColorStop() method specifies the color stop, described by coordinates, which can be 0 to 1.

To use a gradient, set fillStyle or strokeStyle to a gradient and then draw a shape, such as a rectangle, text, or a line.

Use the createLinearGradient () :

Example: Create a linear gradient. Fill the rectangle with gradient:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
 
// Create a gradient
var grd=ctx.createLinearGradient(0.0.200.0);
grd.addColorStop(0."red");
grd.addColorStop(1."white");
 
// Fill the gradient
ctx.fillStyle=grd;
ctx.fillRect(10.10.150.80);
Copy the code

Use the createRadialGradient () :

Example: Create a radial/circular gradient. Fill the rectangle with gradient:

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
 
// Create a gradient
var grd=ctx.createRadialGradient(75.50.5.90.60.100);
grd.addColorStop(0."red");
grd.addColorStop(1."white");
 
// Fill the gradient
ctx.fillStyle=grd;
ctx.fillRect(10.10.150.80);
Copy the code

To place an image on the canvas, use the following methods:

  • drawImage(image,x,y)
var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
var img=document.getElementById("scream");
ctx.drawImage(img,10.10);
Copy the code

 

 

HTML 5 inline SVG

HTML5 supports inline SVG.

<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="130px" width="500px">
   <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" style="Stop - color: RGB (255255, 0). stop-opacity:1">
                <stop offset="100%" style="Stop - color: RGB (0, 255); stop-opacity:1">
                </stop>
            </stop>
        </linearGradient>
   </defs>
   <ellipse cx="300" cy="70" rx="85" ry="55" fill="url(#grad1)">
        <text fill="#ffffff" font-size="45" font-family="Verdana" 
            x="250" y="86" 
            data-darkreader-inline-fill="" 
            style="--darkreader-inline-fill:#ffffff;">
            SVG
        </text>
        Sorry, your browser does not support inline SVG.
    </ellipse>
</svg>
Copy the code
  • SVG stands for Scalable Vector Graphics
  • SVG is used to define vector-based graphics for networking
  • SVG uses XML format to define graphics
  • SVG images do not lose graphical quality when they are enlarged or resized
  • SVG is the World Wide Web Consortium standard

 

The advantages of using SVG over other image formats, such as JPEG and GIF, are:

  • SVG images can be created and modified using a text editor
  • SVG images can be searched, indexed, scripted, or compressed
  • SVG is scalable
  • SVG images can be printed with high quality at any resolution
  • SVG can be enlarged without degrading image quality

In HTML5, you can embed SVG elements directly into HTML pages:

<! DOCTYPEhtml>
<html>
<body>
 
<svg xmlns="http://www.w3.org/2000/svg" version="1.1" height="190">
  <polygon points="100,10, 40,180, 190,60, 10,60, 160,180"
  style="fill:lime; stroke:purple; stroke-width:5; fill-rule:evenodd;">
</svg>
 
</body>
</html>
Copy the code

 

Differences between SVG and Canvas:

SVG is a language for describing 2D graphics using XML.

Canvas uses JavaScript to draw 2D graphics.

SVG is based on XML, which means that every element in the SVG DOM is available. You can attach JavaScript event handlers to an element.

In SVG, every graph that is drawn is treated as an object. If the attributes of an SVG object change, the browser can reproduce the graphics automatically.

Canvas is rendered pixel by pixel. In canvas, once the graph has been drawn, it doesn’t continue to get attention from the browser. If its position changes, the entire scene also needs to be redrawn, including any objects that may have been covered by the graph.

 

Comparison between Canvas and SVG

Canvas

  • Resolution dependent
  • Event handlers are not supported
  • Weak text rendering capability
  • Ability to save the resulting image in.png or.jpg format
  • Best suited for graphics-intensive games, where many objects are frequently redrawn

SVG

  • Resolution independent
  • Support event handlers
  • Best for applications with large rendered areas (such as Google Maps)
  • High complexity slows down rendering (any application that overuses DOM is not fast)
  • Not suitable for game applications

 

 

HTML5 Canvas VS svg

Canvas and SVG both allow you to create graphics in your browser, but they are fundamentally different.

 

SVG

SVG is a language for describing 2D graphics using XML.

SVG is based on XML, which means that every element in the SVG DOM is available. You can attach JavaScript event handlers to an element.

In SVG, every graph that is drawn is treated as an object. If the attributes of an SVG object change, the browser can reproduce the graphics automatically.

Canvas

Canvas uses JavaScript to draw 2D graphics.

Canvas is rendered pixel by pixel.

In canvas, once the graph has been drawn, it doesn’t continue to get attention from the browser. If its position changes, the entire scene also needs to be redrawn, including any objects that may have been covered by the graph.

 

HTML 5 multimedia

Multimedia on the Web refers to sound, music, video, and animation.

Modern Web browsers already support many multimedia formats.

 

Multimedia elements, such as video and audio, are stored in media files.

The most common way to determine the media type is to look at the file extension. When the browser gets the file extension.htm or.html, it assumes that the file is an HTML page. The.xml extension indicates XML files, while the.css extension indicates stylesheets. Image formats are identified by.gif or.jpg.

Multimedia elements also have file formats with different extensions, such as.swf,.wmv,.mp3, and.mp4.

 

MP4 format is a new Internet video format that will be popularized soon. HTML5, Flash Player and video sites like Youku all support it.

Sound format

WAVE is the most popular uncompressed sound format on the Internet and is supported by all popular browsers. If you need uncompressed sound (music or speech), you should use WAVE.

MP3 is the latest compressed recorded music format. The term MP3 has become synonymous with digital music. If your url is engaged in recording music, then MP3 is an option.

 

 

HTML 5 Object element

<object> is used to support HTML assistants (plug-ins).

 

HTML Assistant (plug-in)

Helper applications are programs that can be launched by a browser. Ancillary applications are also called plug-ins.

Assistive programs can be used to play audio and video (among other things). Helper programs are loaded using tags.

One advantage of using assistive programs to play video and audio is that you can allow the user to control some or all of the playback Settings.

Most assistive applications allow manual (or programmatic) control of volume Settings and playback functions such as back, pause, stop, and play.

Use QuickTime to play Wave audio

<object width="420" height="360"
classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="bird.wav" />
<param name="controller" value="true" />
</object>
Copy the code

Use QuickTime to play MP4 videos

<object width="420" height="360"
classid="clsid:02BF25D5-8C17-4B23-BC80-D3488ABDDC6B"
codebase="http://www.apple.com/qtactivex/qtplugin.cab">
<param name="src" value="movie.mp4" />
<param name="controller" value="true" />
</object>
Copy the code

Use Flash to play SWF videos

<object width="400" height="40"
classid="clsid:d27cdb6e-ae6d-11cf-96b8-444553540000"
codebase="Http://fpdownload.macromedia.com/ pub/rest/cabs/flash/swflash cab# 8,0,0,0 version =">
<param name="SRC" value="bookmark.swf">
<embed src="bookmark.swf" width="400" height="40"></embed>
</object>
Copy the code

Use Windows Media Player to play WMV movies

<object width="100%" height="100%"
type="video/x-ms-asf" url="3d.wmv" data="3d.wmv"
classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6">
<param name="url" value="3d.wmv">
<param name="filename" value="3d.wmv">
<param name="autostart" value="1">
<param name="uiMode" value="full" />
<param name="autosize" value="1">
<param name="playcount" value="1">
<embed type="application/x-mplayer2" src="3d.wmv" width="100%"
 height="100%" autostart="true" showcontrols="true" 
pluginspage="http://www.microsoft.com/Windows/MediaPlayer/"></embed>
</object>
Copy the code

HTML 5 Audio Audio

HTML5 provides a standard for playing audio files.

Until now, there was no standard for audio playback on web pages.

Today, most audio is played through plug-ins such as Flash. However, not all browsers have the same plug-ins.

HTML5 sets the standard for embedding audio elements on web pages, that is, using elements.

 

Browser support

Elements are supported by Internet Explorer 9+, Firefox, Opera, Chrome, and Safari.

Note: Elements are not supported by Internet Explorer 8 and earlier VERSIONS of IE.

Play audio:

<audio controls>
  <source src="horse.ogg" type="audio/ogg">
  <source src="horse.mp3" type="audio/mpeg">Your browser does not support the audio element.</audio>
Copy the code

The control property lets you add play, pause, and volume controls.

Between
you need to insert prompt text for

The

 

Element supports files in three audio formats: MP3, Wav, and Ogg

MIME type of audio format

HTML 5 Audio tags

 

HTML 5 Video Video

Many sites use video. HTML5 provides the standard for presenting video.

Until now, there was no standard for displaying video on web pages.

Today, most video is displayed through plug-ins such as Flash. However, not all browsers have the same plug-ins.

HTML5 provides a standard way to include video through the video element.

 

Display video in HTML5

<video width="320" height="240" controls>
    <source src="movie.mp4" type="video/mp4">
    <source src="movie.ogg" type="video/ogg">Your browser does not support the Video TAB.</video>
Copy the code

The Video element provides play, pause, and volume controls to control the video.

The video element also provides width and height attributes to control the size of the video. If the height and width are set, the required video space is retained when the page loads. If these properties are not set, the browser does not know the size of the video, the browser can no longer save a specific space when loading, and the page will change based on the size of the original video.

The content inserted between the
tags is intended for display by browsers that do not support the video element.

The

 

The element supports three video formats: MP4, WebM, and Ogg:

  • MP4 = MPEG 4 files with H.264 video encoding and AAC audio encoding
  • WebM = WebM file with VP8 video encoding and Vorbis audio encoding
  • Ogg = Ogg file with Theora video encoding and Vorbis audio encoding

Video format

HTML5 – Use DOM for control

HTML5

Methods, attributes, and events of the

The methods are used to play, pause, and load. Properties (such as duration, volume, etc.) can be read or set. DOM events can tell you, for example, that the

The simple method in this example shows how to use the

Create simple play/pause and resize controls for your video:

Play/Pause Zoom in and out normal

<div class="example_code notranslate">
  <br>
  <div style="text-align:center"> 
  <button onclick="playPause()">Play/Pause</button> 
  <button onclick="makeBig()">amplification</button>
  <button onclick="makeSmall()">narrow</button>
  <button onclick="makeNormal()">ordinary</button>
  <br><br> 
  <video id="video1" width="480">
    <source src="https://www.w3schools.com/html/mov_bbb.mp4" type="video/mp4">
    <source src="https://www.w3schools.com/html/mov_bbb.ogg" type="video/ogg">Your browser does not support HTML5 video.</video>
</div> 
<script> 
    var myVideo=document.getElementById("video1"); 
    function playPause(){ 
        if (myVideo.paused) 
            myVideo.play(); 
        else 
            myVideo.pause(); 
    } 
    function makeBig() { 
        myVideo.width=600; 
    } 
    function makeSmall(){ 
        myVideo.width=320; 
    } 
    function makeNormal(){ 
        myVideo.width=480; 
    } 
</script> 
Copy the code

HTML 5 Video element

 

HTML5’s new input type

HTML5 has several new form input types. These new features provide better input control and validation.

This chapter provides a comprehensive overview of these new input types:

  • color
  • date
  • datetime
  • datetime-local
  • email
  • month
  • number
  • range
  • search
  • tel
  • time
  • url
  • week

 color

The color type is used in the input field to select the color, as shown below:

Select a color from the color picker:

Choose the color you like:<input type="color" name="favcolor">
Copy the code

date

The date type allows you to select a date from a date picker.

Define a time controller:

Birthday:<input type="date" name="bday">
Copy the code

datetime

The Datetime type allows you to select a date (UTC time).

Define a date and time controller (local time) :

Birthday (date and time):<input type="datetime" name="bdaytime">
Copy the code

datetime-local

The datetime-local type allows you to select a date and time (no time zone).

Birthday (date and time):<input type="datetime-local" name="bdaytime">
Copy the code

email

The email type is used for input fields that should contain E-mail addresses.

When submitting the form, the email field values are automatically verified to be valid:

E-mail: <input type="email" name="email">
Copy the code

month

The month type allows you to select a month.

Define month and year (no time zone):

Birthday (month and year):<input type="month" name="bdaymonth">
Copy the code

number

The number type is used for input fields that should contain numeric values.

You can also set limits on the numbers you accept:

Define a numeric input field (qualified):

Quantity (between 1 and 5):<input type="number" name="quantity" min="1" max="5">
Copy the code

Use the following attributes to qualify numeric types:

range

The range type is used for input fields that should contain a range of numeric values.

The range type is displayed as a slider.

Define a value that does not need to be very precise (similar to slider control) :

<input type="range" name="points" min="1" max="10">
Copy the code

Use the following attributes to qualify numeric types:

  • Max – Specifies the maximum allowed value
  • Min – Specifies the minimum allowable value
  • Step – Specifies the legal number interval
  • Value – Specifies the default value

search

The search type is used to search domains, such as site search or Google search.

Define a search field (similar to a site search or Google search):

Search Google: <input type="search" name="googlesearch">
Copy the code

tel

Define the input phone number field:

Telephone No. :<input type="tel" name="usrtel">
Copy the code

time

The time type allows you to select a time.

Define an inputable time controller (no time zone) :

Selection time:<input type="time" name="usr_time">
Copy the code

url

Url types are used for input fields that should contain URL addresses.

When the form is submitted, the value of the URL field is automatically validated.

Define the input URL field:

Add your home page:<input type="url" name="homepage">
Copy the code

week

The week type allows you to select the week and year.

Define week and year (no time zone):

Week of choice:<input type="week" name="week_year">
Copy the code

 

 

HTML5 form Elements

HTML5 has the following new form elements:

<datalist>
<keygen>
<output>
Copy the code

The < datalist> element specifies the list of options for the input field.

The < datalist> property specifies that the form or input field should have auto-complete functionality. When the user starts typing in the autocomplete field, the browser should display the options filled in in that field:

Bind to the element using the list attribute of the element.

elements use predefined values:

<input list="browsers">
<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>
Copy the code

The purpose of the < keygen> element is to provide a reliable way to authenticate users.

The < keyGen > tag specifies the key pair generator field for the form.

When the form is submitted, two keys are generated, a private key and a public key.

The private key is stored on the client.

The public key is sent to the server.

The public key can then be used to validate the user’s client certificate.

Form with keyGen field:

<form action="demo_keygen.asp" method="get">User name:<input type="text" name="usr_name">Encryption:<keygen name="security">
<input type="submit">
</form>
Copy the code

The element is used for different types of output, such as computational or script output:

Display the calculated results in the element:

<form oninput="x.value=parseInt(a.value)+parseInt(b.value)">0
<input type="range" id="a" value="50">100 +
<input type="number" id="b" value="50">=
<output name="x" for="a b"></output>
</form>
Copy the code

 

 

HTML5 Form Attributes

HTML5’s

and
tags add several new attributes.

New property:
  • autocomplete
  • novalidate

New property:

  • autocomplete
  • autofocus
  • form
  • formaction
  • formenctype
  • formmethod
  • formnovalidate
  • formtarget
  • The height and width
  • list
  • Min and Max
  • multiple
  • pattern (regexp)
  • placeholder
  • required
  • step

 

The autocomplete property specifies that the form or input field should have auto-complete functionality.

When the user starts typing in the autocomplete field, the browser should display the options filled in in that field.

Tip: It is possible for the Autocomplete attribute to be on in the form element and off in the input element.

Note: Autocomplete works with

tags, and with
tags of the following types: Text, search, URL, telephone, email, password, Datepickers, range and color.

Turn autoComplete on in HTML Form (an input field turns autoComplete off):

<form action="demo-form.php" autocomplete="on">
  First name:<input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  E-mail: <input type="email" name="email" autocomplete="off"><br>
  <input type="submit">
</form>
Copy the code

The novalidate attribute is a Boolean attribute.

The novalidate attribute states that the form or input fields should not be validated when submitting the form.

There is no need to validate submitted form data

<form action="demo-form.php" novalidate>
  E-mail: <input type="email" name="user_email">
  <input type="submit">
</form>
Copy the code

The Autofocus attribute is a Boolean attribute.

The Autofocus attribute specifies that the domain automatically gets focus when the page loads.

Make the “First name” input field autofocus when the page loads:

first name:<input  type="text"  name="fname"  autofocus\ >
Copy the code

The form property specifies one or more forms to which the input field belongs.

Tip: If you want to reference more than one form, use a space-separated list.

The input field outside the form refers to the HTML form (which is still part of the form form):

<form action="demo-form.php" id="form1">
  First name: <input type="text" name="fname"><br>
  <input type="submit" value="Submit">
</form>
 
Last name: <input type="text" name="lname" form="form1">
Copy the code

The FormAction property is used to describe The URL to submit The form.

The FormAction property overrides The action property in The element.

Note: The formAction property is used for type= “submit” and type= “image”.

The following HTMLform contains two submit buttons for different addresses:

<form action="demo-form.php">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit"><br>
  <input type="submit" formaction="demo-admin.php"
  value="Submit">
</form>
Copy the code

The formencType attribute describes the data encoding that the form submits to the server (only for the method= “post” form in the form form).

The formencType attribute overrides the encType attribute of the form element.

Main: This property is used in conjunction with type= “submit” and type= “image”.

The first submit button sends form data encoded by default, and the second submit button sends form data encoded in “multipart/form-data” :

<form action="demo-post_enctype.php" method="post">
  First name: <input type="text" name="fname"><br>
  <input type="submit" value="Submit">
  <input type="submit" formenctype="multipart/form-data"
  value="Submit as Multipart/form-data">
</form> 
Copy the code

The FormMethod property defines how the form is submitted.

The formMethod attribute overrides the element’s method attribute.

Note: This property can be used with type= “submit” and type= “image”.

Example of redefining form submission:

<form action="demo-form.php" method="get">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Submit">
  <input type="submit" formmethod="post" formaction="demo-post.php"
  value="Submit using POST">
</form>
Copy the code

The novalidate attribute is a Boolean attribute.

The novalidate attribute describes how elements do not need to be validated when the form is submitted.

The formNovalidate attribute overrides the element’s novalidate attribute.

Note: The formnovalidate attribute is used with type= “submit”

Form with two submit buttons (with and without validation):

<form action="demo-form.php">
  E-mail: <input type="email" name="userid"><br>
  <input type="submit" value="Submit"><br>
  <input type="submit" formnovalidate value="Do not validate submit">
</form>
Copy the code

The formTarget property specifies a name or a keyword to indicate the presentation of form submission data after it is received.

The formTarget attribute overrides

The target attribute of the element.

Note: The formTarget attribute is used with type= “submit” and type= “image”.

A form with two submit buttons, displayed in different Windows:

<form action="demo-form.php">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br>
  <input type="submit" value="Normal submission">
  <input type="submit" formtarget="_blank"
  value="Submit to a new page">
</form>
Copy the code

The height and width attributes specify the image height and width to be used for tags of type image.

Note: The height and width attributes only apply to tags of type image.

Tip: Images usually specify both height and width attributes. If the image is set to height and width, the space required by the image is preserved when the page is loaded. Without these attributes, the browser does not know the size of the image and cannot reserve proper space. Images change the page layout during loading (even though they are loaded).

<input type="image" src="img_submit.gif" alt="Submit" width="48" height="48">
Copy the code

The list attribute specifies the datalist of the input field. Datalist is alist of options for the input field.

Predefined values in :

<input list="browsers">
<datalist id="browsers">
  <option value="Internet Explorer">
  <option value="Firefox">
  <option value="Chrome">
  <option value="Opera">
  <option value="Safari">
</datalist>
Copy the code

The min, Max, and step attributes are used to specify restrictions (constraints) for input types that contain numbers or dates.

Note: The min, Max, and step attributes apply to the following types of tags: Date pickers, Number, and range.

Set minimum and maximum values for elements:

nter a date before 1980-01-01:
<input type="date" name="bday" max="1979-12-31">
Enter a date after 2000-01-01:
<input type="date" name="bday" min="2000-01-02">
Quantity (between 1 and 5):
<input type="number" name="quantity" min="1" max="5">
Copy the code

The multiple attribute is a Boolean attribute.

The multiple attribute specifies that multiple values can be selected in an element.

Note that the multiple attribute applies to the following types of tags: email and File:

Upload multiple files:

Select images: <input type="file" name="img" multiple>
Copy the code

The pattern attribute describes a regular expression used to validate the value of an element.

Note: The Pattern attribute applies to tags of the following types: text, search, URL, tel, email, and password.

Tip: the global title attribute is used to describe the pattern.

Country code: <input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">
Copy the code

The placeholder property provides a hint about the expected value of the input field.

A short prompt is displayed on the input field before the user enters a value.

Note: placeholder attributes apply to the following types of tags: text, search, URL, telephone, email, and password.

Input field prompt text:

<input type="text" name="fname" placeholder="First name">
Copy the code

The Required attribute is a Boolean attribute.

The Required attribute states that the input field (which cannot be empty) must be filled in before submission.

Note: The required attribute applies to the following types of tags: text, search, URL, telephone, email, password, date pickers, Number, checkbox, radio, and file.

Input fields that cannot be empty:

Username: <input type="text" name="usrname" required>
Copy the code

The step property specifies the legal number interval for the input field.

If step= “3”, the legal numbers are -3,0,3,6, etc

Tip: The step attribute can create a region value with the Max and min attributes.

Note: The step attribute is used with the following type types: number, range, date, Datetime, datetime-local, month, time, and week.

Set the input step to be 3:

<input type="number" name="points" step="3">
Copy the code

 

 

HTML5 Geolocation

HTML5 Geolocation is used to locate a user’s location.

 

The HTML5 Geolocation API is used to get the user’s geographical location.

Because this feature may violate user privacy, user location information is not available unless the user consents.

 

Use the getCurrentPosition() method to get the user’s location.

The following example is a simple geolocation example that returns the longitude and latitude of the user’s location:

var x=document.getElementById("demo");
function getLocation()
{
    if (navigator.geolocation)
    {
        navigator.geolocation.getCurrentPosition(showPosition);
    }
    else
    {
        x.innerHTML="This browser does not support geolocation."; }}function showPosition(position)
{
    x.innerHTML="Latitude:" + position.coords.latitude + 
    

Longitude:
+ position.coords.longitude; Copy the code

The second argument to the getCurrentPosition() method is used to handle errors. This specifies the function to run when the user location fails to be retrieved:

function showError(error)
{
    switch(error.code) 
    {
        case error.PERMISSION_DENIED:
            x.innerHTML="User rejects geolocation request."
            break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is not available."
            break;
        case error.TIMEOUT:
            x.innerHTML="Request user geolocation timed out."
            break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="Unknown error."
            break; }}Copy the code

To display the results in a map, you need to access a map service that uses latitude and longitude, such as Google Map or Baidu Map:

function showPosition(position)
{
    var latlon=position.coords.latitude+","+position.coords.longitude;
 
    var img_url="http://maps.googleapis.com/maps/api/staticmap?center="
    +latlon+"&zoom=14&size=400x300&sensor=false";
    document.getElementById("mapholder").innerHTML="<img src='"+img_url+"' >";
}
Copy the code

If successful, the getCurrentPosition() method returns the object. The attributes latitude, longitude, and Accuracy are always returned. If available, the other properties below are returned.

WatchPosition () – Returns the user’s current position and continues to return the updated position as the user moved (like GPS on a car).

ClearWatch () – Stops the watchPosition() method

The following example shows the watchPosition() method. You need an accurate GPS device to test this example (like an iPhone) :

var x=document.getElementById("demo");
function getLocation(){
    if (navigator.geolocation) {
        navigator.geolocation.watchPosition(showPosition);
    } else {
        x.innerHTML="This browser does not support geolocation."; }}function showPosition(position){
    x.innerHTML="Latitude:" + position.coords.latitude + 
    

Longitude:
+ position.coords.longitude; } Copy the code

 

HTML 5 drag and drop

Drag and drop (Drag and drop) are part of the HTML5 standard.

Drag and drop is a common feature where you grab an object and drag it to another location.

In HTML5, drag and drop is part of the standard, and any element can be dragged and dropped.

<! DOCTYPEHTML>
<html>
    <head>
        <meta charset="utf-8"> 
        <title>Sun Called beast's blog</title>
        <style type="text/css">
            #div1 {width:350px;height:70px;padding:10px;border:1px solid #aaaaaa; }</style>
        <script>
            function allowDrop(ev)
            {
                ev.preventDefault();
            }
            
            function drag(ev)
            {
                ev.dataTransfer.setData("Text",ev.target.id);
            }
            
            function drop(ev)
            {
                ev.preventDefault();
                var data=ev.dataTransfer.getData("Text");
                ev.target.appendChild(document.getElementById(data));
            }
        </script>
    </head>
    <body>
    
    <p>Drag an image into a rectangle:</p>
    <div id="div1" ondrop="drop(event)" ondragover="allowDrop(event)"></div>
    <br>
    <img id="drag1" src="/images/logo.png" draggable="true" ondragstart="drag(event)" width="336" height="69">
    </body>
</html>
Copy the code

First, to make the element dragable, set the draggable property to true:

<img draggable="true">
Copy the code

Then, specify what happens when the element is dragged.

In the example above, the onDragStart property calls a function, drag(event), which specifies the data to be dragged.

The datatransfer.setData () method sets the data type and value of the data being dragged:

function drag(ev)  
{  
    ev.dataTransfer.setData("Text",ev.target.id);  
}
Copy the code

The onDragover event specifies where to place the dragged data.

By default, data/elements cannot be placed in other elements. If we want to set to allow placement, we must prevent the default handling of elements.

This is done by calling the event.preventDefault() method of the ondragover event:

event.preventDefault()
Copy the code

A DROP event occurs when data is dropped.

In the example above, the ondrop attribute calls a function, drop(event) :

function drop(ev)  
{  
    ev.preventDefault();  
    var data=ev.dataTransfer.getData("Text");  
    ev.target.appendChild(document.getElementById(data));  
}
Copy the code
  • Call preventDefault() to avoid the browser’s default handling of the data (the default behavior of the drop event is to open as a link)
  • The dragged data is obtained through the datatransfer.getData (” Text “) method. This method returns any data set to the same type in the setData() method.
  • The dragged data is the ID of the element being dragged (” drag1 “)
  • Appends the dragged element to the placed element (the target element)

 

HTML 5 Web store

 

HTML5 Web storage, a better local storage than cookies.

 

Using HTML5, you can store the user’s browsing data locally.

Earlier, cookies were used for local storage. But Web storage needs to be more secure and fast. This data is not stored on the server, but is only used when users request web site data. It can also store large amounts of data without affecting the performance of the site.

Data exists in key/value pairs, and data on a Web page is accessible only to that web page.

 

The two objects where the client stores data are:

  • LocalStorage – Used to store the entire site data for a long time, save data without expiration time, until manual removal.
  • SessionStorage – Used to temporarily store data for the same window (or TAB), which will be deleted after the window or TAB is closed.

Before using web storage, check whether your browser supports localStorage and sessionStorage:

if(typeof(Storage)! = ="undefined")
{
    / / yes! Support localStorage sessionStorage objects!
    // Some code.....
} else {
    / / I'm sorry! Web storage is not supported.
}
Copy the code

The data stored by the localStorage object has no time limit. The data is still available the next day, the next week, or the next year.

localStorage.sitename="Sun's Blog";
document.getElementById("result").innerHTML="Website name:" + localStorage.sitename;
Copy the code
  • Create a localStorage key/value pair using key= “sitename” and value= “www.axihe.com”.
  • Retrieves the key value “sitename” and inserts the data into the element with id= “result”.

The above example could also be written like this:

/ / store
localStorage.sitename = "Asi River Front Course";
/ / to find
document.getElementById("result").innerHTML = localStorage.sitename;
Copy the code

Remove sitename from localStorage:

localStorage.removeItem("sitename");
Copy the code

Both localStorage and sessionStorage use the same API. Common apis are as follows (take localStorage as an example) :

  • SetItem (key,value) to save data.
  • Read data: localstorage.getitem (key);
  • Delete a single item: localstorage.removeItem (key);
  • Delete all data: localstorage.clear ();
  • Get the key of an index: localstorage.key (index);

Tip: Key/value pairs are usually stored as strings, which you can convert to suit your needs.

The following example shows the number of times the user clicked the button.

String values in the code are converted to numeric types:

if (localStorage.clickcount){
    localStorage.clickcount=Number(localStorage.clickcount)+1;
}else{
    localStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You've clicked the button." + 
    localStorage.clickcount + "Time";
Copy the code

The sessionStorage method stores data for a session. When the user closes the browser window, the data is deleted.

How to create and access a sessionStorage:

if (sessionStorage.clickcount){
    sessionStorage.clickcount=Number(sessionStorage.clickcount)+1;
}else{
    sessionStorage.clickcount=1;
}
document.getElementById("result").innerHTML="You've already clicked that button in this session." + 
    sessionStorage.clickcount + "Time";
Copy the code

Website listing program to achieve the following functions:

  • You can enter the site name, url, to the site name as a key to store localStorage;
  • According to the website name, find the url;
  • Lists all the sites that are currently saved;

The following code is used to save the lookup data:

Save () and find() methods

// Save data
function save(){  
    var siteurl = document.getElementById("siteurl").value;  
    var sitename = document.getElementById("sitename").value;  
    localStorage.setItem(sitename, siteurl);
    alert("Added successfully");
}
// Find data
function find(){  
    var search_site = document.getElementById("search_site").value;  
    var sitename = localStorage.getItem(search_site);  
    var find_result = document.getElementById("find_result");  
    find_result.innerHTML = search_site + The url of "is:" + sitename;  
}
Copy the code

Complete example:

<div style="border: 2px dashed #ccc; width:320px; text-align:center;">     
    <label for="sitename">Key:</label>  
    <input type="text" id="sitename" name="sitename" class="text"/>  
    <br/>  
    <label for="siteurl">Web site (value) :</label>  
    <input type="text" id="siteurl" name="siteurl"/>  
    <br/>  
    <input type="button" onclick="save()" value="New Record"/>  
    <hr/>  
    <label for="search_site">Enter the site name:</label>  
    <input type="text" id="search_site" name="search_site"/>  
    <input type="button" onclick="find()" value="Find a website"/>  
    <p id="find_result"><br/></p>  
</div>
Copy the code

Next we’ll store object data using json.stringify, which converts objects to strings.

var  site = new  Object; .var  str = JSON.stringify(site); // Convert an object to a string
Copy the code

We then convert the string to a JSON object using the json.parse method:

var site = JSON.parse(str);
Copy the code
// Save data
function save(){  
    var site = new Object;
    site.keyname = document.getElementById("keyname").value;
    site.sitename = document.getElementById("sitename").value;  
    site.siteurl = document.getElementById("siteurl").value;
    var str = JSON.stringify(site); // Convert an object to a string
    localStorage.setItem(site.keyname,str);  
    alert("Saved successfully");
}  
// Find data
function find(){  
    var search_site = document.getElementById("search_site").value;  
    var str = localStorage.getItem(search_site);  
    var find_result = document.getElementById("find_result");
    var site = JSON.parse(str);  
    find_result.innerHTML = search_site + The site name of "" is: + site.sitename + ", the url is:" + site.siteurl;  
}
Copy the code

Complete sample

<div style="border: 2px dashed #ccc; width:320px; text-align:center;">
    <label for="keyname">Alias (key) :</label>  
    <input type="text" id="keyname" name="keyname" class="text"/>  
    <br/>  
    <label for="sitename">The websites:</label>  
    <input type="text" id="sitename" name="sitename" class="text"/>  
    <br/>  
    <label for="siteurl">Web site:</label>  
    <input type="text" id="siteurl" name="siteurl"/>  
    <br/>  
    <input type="button" onclick="save()" value="New Record"/>  
    <hr/>  
    <label for="search_site">Enter the alias (key) :</label>  
    <input type="text" id="search_site" name="search_site"/>  
    <input type="button" onclick="find()" value="Find a website"/>  
    <p id="find_result"><br/></p>  
</div>
Copy the code

LoadAll outputs all stored data. You need to make sure that localStorage stores all data in JSON format, otherwise json.parse (STR) will report an error.

 

HTML5 application caching

Using HTML5, you can easily create offline versions of web applications by creating cache manifest files.

 

HTML5 introduces application caching, which means web applications can be cached and accessed without an Internet connection.

Application caching brings three advantages to applications:

  1. Offline browsing – Users can use them while the application is offline
  2. Speed – Cached resources load faster
  3. Reduce server load – The browser will only download updated or changed resources from the server.

The following example shows an HTML document with cache manifest (for offline viewing) :

<! DOCTYPEHTML>
<html manifest="demo.appcache">
<body>Document contents......</body>
</html>
Copy the code

To enable application caching, include the manifest attribute in the document’s tag:

<! DOCTYPEHTML>
<html manifest="demo.appcache">.</html>
Copy the code

Each page specified with the MANIFEST is cached when the user accesses it. If the manifest attribute is not specified, the page is not cached (unless the page is specified directly in the MANIFEST file).

The recommended file extension for the manifest file is “.appcache “.

Note that the manifest file needs to be configured with the correct MIME-type, which is “text/cache-manifest”. The configuration must be done on the Web server.

 

The manifest file is a simple text file that tells the browser what is being cached (and what is not).

The manifest file can be divided into three parts:

  • CACHE MANIFEST– Files listed under this heading will be cached after the first download
  • NETWORK– Files listed under this heading require a connection to the server and will not be cached
  • FALLBACK– Files listed under this heading specify the fallback page when the page is not accessible (such as a 404 page)

1. The first line, CACHE MANIFEST, is required:

CACHE MANIFEST  
/theme.css  
/logo.gif  
/main.js
Copy the code

The manifest file above lists three resources: a CSS file, a GIF image, and a JavaScript file. When the manifest file is loaded, the browser downloads the three files from the root of the site. These resources are then available whenever the user disconnects from the Internet.

2. The following NETWORK section states that the file “login.php” is never cached and is not available offline:

NETWORK:  
login.php
Copy the code

You can use an asterisk to indicate that all other resources/files require an Internet connection:

NETWORK:  
\*
Copy the code

3. The following FALLBACK section specifies that if an Internet connection cannot be established, replace all files in the /html5/ directory with “offline. HTML” :

FALLBACK:  
/html/ /offline.html
Copy the code

Note: The first URI is a resource and the second is a substitute.

 

Update the cache

Once an application is cached, it remains cached until the following happens:

  • The user cleared the browser cache
  • The manifest file has been modified (see hints below)
  • The application cache is updated by the program

Instance – Complete Manifest file

CACHE MANIFEST
# 2012-02-21 v1. 0. 0
/theme.css
/logo.gif
/main.js
NETWORK:
login.php
FALLBACK:
/html/ /offline.html
Copy the code

Be aware of the contents of the cache.

Once the file is cached, the browser continues to show the cached version, even if you modify the file on the server. To ensure that the browser updates the cache, you need to update the manifest file.

 

 

HTML5 websocket

WebSocket is a protocol for full duplex communication over a single TCP connection provided by HTML5.

WebSocket makes it easier to exchange data between the client and the server, allowing the server to actively push data to the client. In the WebSocket API, the browser and server only need to complete a handshake to create a persistent connection and two-way data transfer.

In the WebSocket API, the browser and the server only need to do a handshake, and then a fast channel is formed between the browser and the server. Data can be transmitted directly between the two.

Ajax polling is now used by many web sites to implement push technology. Polling is when the browser makes an HTTP request to the server at a specific time interval (e.g., every 1 second), and the server returns the latest data to the client’s browser. This traditional pattern has obvious disadvantages, namely, the browser needs to make continuous requests to the server. However, HTTP requests may contain long headers, in which only a small portion of the data is really valid, which obviously wastes a lot of bandwidth and other resources.

The WebSocket protocol defined by HTML5 can better save server resources and bandwidth, and can communicate in more real time.

The browser sends a request to the server to establish a WebSocket connection through JavaScript. After the connection is established, the client and server can exchange data directly through the TCP connection.

When you get a Web Socket connection, you can send data to the server using the send() method and receive the data returned by the server using the onMessage event.

The following APIS are used to create WebSocket objects.

var Socket = new WebSocket(url, [protocol] );
Copy the code

The first parameter, url, specifies the URL of the connection. The second parameter, protocol, is optional and specifies an acceptable subprotocol

Properties:

Events:

Methods:

 

The WebSocket protocol is essentially a TCP – based protocol.

To establish a WebSocket connection, the client browser first issues an HTTP request to the server. This request is different from the usual HTTP request and contains some additional header information, including “Upgrade: “WebSocket” indicates that this is an HTTP request for protocol upgrade. The server parses these additional headers and generates a reply message back to the client. The WebSocket connection between the client and the server is established, and the two sides can freely transfer information through this connection channel. And the connection persists until either the client or the server actively closes the connection.

 

Most browsers currently support the WebSocket() interface, so you can try it out in Chrome, Mozilla, Opera, and Safari.

Sunjiaoshou_websocket. HTML File contents

<! DOCTYPEHTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>Sun Called beast's blog</title>
      <script type="text/javascript">
         function WebSocketTest(){
            if ("WebSocket" in window){
               alert("Your browser supports WebSocket!");
               // Open a Web socket
               var ws = new WebSocket("ws://localhost:9998/echo");
               ws.onopen = function(){
                  // The Web Socket is connected, use the send() method to send data
                  ws.send("Send data");
                  alert("Data in transit...");
               };
               ws.onmessage = function (evt) { 
                  var received_msg = evt.data;
                  alert("Data received...");
               };
               ws.onclose = function(){ 
                  / / close the websocket
                  alert("Connection closed..."); 
               };
            }else{
               // Browsers do not support WebSocket
               alert("Your browser does not support WebSocket!"); }}</script>
   </head>
   <body>
      <div id="sse">
         <a href="javascript:WebSocketTest()">Run the WebSocket</a>
      </div>
   </body>
</html>
Copy the code

Install pywebsocket

Before executing the above program, we need to create a service that supports WebSocket. Download mod_pywebsocket from PywebSocket, or use git to download:

git clone https://github.com/google/pywebsocket.git
Copy the code

Mod_pywebsocket requires python environment support

Mod_pywebsocket is an Apache HTTP Web Socket extension. The installation steps are as follows:

  • Unzip the downloaded files.
  • Go to the PyWebSocket directory.
  • Execute command:
$ python setup.py build
$ sudo python setup.py install
Copy the code

View the documentation:

$ pydoc mod_pywebsocket
Copy the code

Open the service

Run the following command in the pywebsocket/mod_pywebsocket directory:

$ sudo python standalone.py -p 9998 -w .. /example/Copy the code

The above command opens a service with port 9998, using -w to set the directory where the handler echo_wsh.py resides.

Now we can open the sunJiaoshou_websocket.html file we created earlier in Chrome. If your browser supports WebSocket(), click “Run WebSocket” and you’ll see a pop-up window for each step of the process.

Process Gif demo:

After we stop the service, it will pop up “Connection closed… “

 

The HTML5 server sends events

HTML5 server-sent events allow web pages to receive updates from the server.

Server-sent event – one-way message passing

Server-sent events refer to web pages that automatically get updates from the Server.

It used to be possible to do this, too, if a web page had to ask if an update was available. By sending events through the server, updates can arrive automatically.

Examples: Facebook/Twitter updates, stock updates, new blog posts, race results, etc.

 

The EventSource object is used by the receiving server to send event notifications:

var source=new EventSource("demo_sse.php");
source.onmessage=function(event){
    document.getElementById("result").innerHTML+=event.data + "<br>";
};
Copy the code
  • Create a new EventSource object and specify the URL of the page to send the updates (in this case, “demo_sse.php”)
  • An onMessage event occurs every time an update is received
  • When the onMessage event occurs, the received data is pushed into the element with id “result”

Detect server-sent event support

if(typeof(EventSource)! = ="undefined") {// Browsers support server-sent
    // Some code.....
}else{
    // Browsers do not support server-sent..
}
Copy the code

Server-side code example

For the above example to work, you also need servers that can send data updates (such as PHP and ASP).

The syntax of the server-side event flow is very simple. Set the “Content-Type” header to “text/event-stream”. You are now ready to send the event stream.


       
header('Content-Type: text/event-stream'); 
header('Cache-Control: no-cache'); 
$time = date('r'); 
echo "data: The server time is: {$time}\n\n"; 
flush(); 
? >
Copy the code

ASP code (VB) (demo_SX.asp):

<%
Response.ContentType="text/event-stream"
Response.Expires=-1
Response.Write("data: " & now())
Response.Flush()
%>
Copy the code
  • Set header “Content-Type” to “text/event-stream”
  • Specifies that pages are not cached
  • Output date sent (always beginning with “data:”)
  • Output data to the page refresh

We use the onMessage event to get the message. But there are other events you can use: