Home > Web Front-end > Front-end Q&A > What are the new features of html5

What are the new features of html5

青灯夜游
Release: 2023-01-28 18:15:30
Original
10761 people have browsed it

The new features of html5 are: 1. Semantic tags (hrader, footer, etc.), which make the content of the page structured and visible; 2. Enhanced forms, with multiple new form inputs Type, which provides better input control and validation; 3. video and audio elements, which provide a standard method for playing video and audio files; 4. Canvas drawing; 5. SVG drawing; 6. Geolocation; 7. Drag and drop API ; 8. Web Worker; 9. Web Storage, etc.

What are the new features of html5

The operating environment of this tutorial: Windows 7 system, HTML5 version, Dell G3 computer.

Top Ten New Features of HTML5

In order to better handle today's Internet applications, HTML5 has added many new elements and functions, such as: graphics drawing, multimedia content, better page structure, better form handling, and several APIs for dragging and dropping elements, positioning, including web application caching, storage, web workers, etc.

( 1) Semantic tags

 Semantic tags make the content of the page structured and well-known

##
##Used to describe the details of a document or a certain part of the documentThe tag contains the details element TitleDefine dialog box, such as prompt box
## Tag Description
Defines the head area of ​​the document
Defines the tail area of ​​the document
Define document navigation
Define sections (sections, sections) in the document
Define independent content areas of the page
Define the sidebar content of the page
##

(2) Enhanced form

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

Input field for numerical valuesInput field for numerical values ​​within a certain rangeUsed for search domainDefine the input phone number fieldSelect a time##urlweek## HTML5 also Add the following form elements

Input type

Description

color

Mainly used to select colors

#date

Select a date from a date picker

datetime

Select a date (UTC time)

datetime-local

Select a date and time (no time zone)

email

Input field containing e-mail address

month

Select a month
##number

range

search

tel

time

URL Address input field

Select the week and year

Form elementDescription

 HTML5’s new form attribute

    • placehoder attribute, a short prompt will be displayed on the input field before the user enters the value. That is, our common default prompt of the input box disappears after the user inputs.
    • required attribute is a boolean attribute. The input field required to be filled in cannot be empty. The
    • pattern attribute describes a regular expression used to verify the value of the element.
    • min and max attributes, set the minimum and maximum value of the element.
    • step attribute specifies the legal number interval for the input field.
    • The height and width attributes are used for the image height and width of the tag of type image.
    • The autofocus attribute is a boolean attribute. Specifies that the field automatically gains focus when the page loads.
    • multiple attribute is a boolean attribute. Specifies that multiple values ​​can be selected within the element.

(3) Video and audio

  • HTML5 provides a standard for playing audio files , that is, use the control attribute of the

to add play, pause and volume controls.

Between you need to insert the prompt text of the

The

Currently, the

  • HTML5 specifies a standard way to include video through the video element.
    <video width="320" height="240" controls>
      <source src="movie.mp4" type="video/mp4">
      <source src="movie.ogg" type="video/ogg">
    您的浏览器不支持Video标签。
    </video>
    Copy after login

    control provides play, pause and volume controls to control the video. You can also use DOM operations to control the playback and pause of the video, such as the play() and pause() methods.

    At the same time, 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 will be reserved when the page is loaded. If these properties are not set and the browser does not know the size of the video, the browser will not be able to reserve a specific space when loading, and the page will change based on the size of the original video. The content inserted between the

    and tags is provided for display by browsers that do not support the video element.

    The video element supports multiple source elements. Elements can link different video files. The browser will use the first recognized format (MP4, WebM, and Ogg)

(4)Canvas drawing

Labels are just graphics containers, and scripts must be used to draw graphics.

Canvas - Graphics

1. Create a canvas. A canvas is a rectangular box in a web page, drawn through the element. By default elements have no borders and no content.

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

Tags usually need to specify an id attribute (often referenced in scripts), width and height attributes define the size of the canvas, and use the style attribute to add a border. You can use multiple elements in an HTML page

2. Use Javascript to draw images. The canvas element itself has no drawing capabilities. All drawing work must be done inside JavaScript

<script>
  var c=document.getElementById("myCanvas");
  var ctx=c.getContext("2d");
  ctx.fillStyle="#FF0000";
  ctx.fillRect(0,0,150,75);
</script>
Copy after login

The getContext("2d") object is a built-in HTML5 object, with a variety of drawing paths, rectangles, circles, characters and additions Image method.

Setting the fillStyle property can be a CSS color, gradient, or pattern. The default fillStyle setting is #000000 (black). The fillRect(x,y,width,height) method defines the current filling method of the rectangle. Meaning: Draw a 150x75 rectangle on the canvas, starting from the top left corner (0,0).

Canvas - Path

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

moveTo(x,y) Define the starting coordinates of the line

lineTo(x,y) Define the ending coordinates of the line

To draw a line we must use the "ink" method, just like stroke ().

<script>
    var c=document.getElementById("myCanvas");
    var ctx=c.getContext("2d");
    ctx.moveTo(0,0);
    ctx.lineTo(200,100);
    ctx.stroke();
</script>
Copy after login

    定义开始坐标(0,0), 和结束坐标 (200,100). 然后使用 stroke() 方法来绘制线条

Canvas - 文本

使用 canvas 绘制文本,重要的属性和方法如下:

  font - 定义字体

  fillText(text,x,y) - 在 canvas 上绘制实心的文本

  strokeText(text,x,y) - 在 canvas 上绘制空心的文本

使用 fillText():

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");
ctx.font="30px Arial";
ctx.fillText("Hello World",10,50);
Copy after login

  使用 "Arial" 字体在画布上绘制一个高 30px 的文字(实心)

Canvas - 渐变

渐变可以填充在矩形, 圆形, 线条, 文本等等, 各种形状可以自己定义不同的颜色。

以下有两种不同的方式来设置Canvas渐变:

  createLinearGradient(x,y,x1,y1) - 创建线条渐变

  createRadialGradient(x,y,r,x1,y1,r1) - 创建一个径向/圆渐变

当我们使用渐变对象,必须使用两种或两种以上的停止颜色。

addColorStop()方法指定颜色停止,参数使用坐标来描述,可以是0至1.

使用渐变,设置fillStyle或strokeStyle的值为渐变,然后绘制形状,如矩形,文本,或一条线。

var c=document.getElementById("myCanvas");
var ctx=c.getContext("2d");

// Create gradient
var grd=ctx.createLinearGradient(0,0,200,0);
grd.addColorStop(0,"red");
grd.addColorStop(1,"white");

// Fill with gradient
ctx.fillStyle=grd;
ctx.fillRect(10,10,150,80);
Copy after login

  创建了一个线性渐变,使用渐变填充矩形

Canvas - 图像

  把一幅图像放置到画布上, 使用 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 after login

  把一幅图像放置到了画布上

(5)SVG绘图

  SVG是指可伸缩的矢量图形

SVG 与 Canvas两者间的区别

  SVG 是一种使用 XML 描述 2D 图形的语言。

  Canvas 通过 JavaScript 来绘制 2D 图形。

  SVG 基于 XML,这意味着 SVG DOM 中的每个元素都是可用的。您可以为某个元素附加 JavaScript 事件处理器。

  在 SVG 中,每个被绘制的图形均被视为对象。如果 SVG 对象的属性发生变化,那么浏览器能够自动重现图形。

  Canvas 是逐像素进行渲染的。在 canvas 中,一旦图形被绘制完成,它就不会继续得到浏览器的关注。如果其位置发生变化,那么整个场景也需要重新绘制,包括任何或许已被图形覆盖的对象。

(6)地理定位

  HTML5 Geolocation(地理定位)用于定位用户的位置。

window.navigator.geolocation {
    getCurrentPosition:  fn  用于获取当前的位置数据
    watchPosition: fn  监视用户位置的改变
    clearWatch: fn  清除定位监视
}   
Copy after login

  获取用户定位信息:

navigator.geolocation.getCurrentPosition(    function(pos){
Copy after login

    console.log('用户定位数据获取成功')
    //console.log(arguments);
    console.log('定位时间:',pos.timestamp)
    console.log('经度:',pos.coords.longitude)
    console.log('纬度:',pos.coords.latitude)
    console.log('海拔:',pos.coords.altitude)
    console.log('速度:',pos.coords.speed)

},    //定位成功的回调function(err){
Copy after login

    console.log('用户定位数据获取失败')
    //console.log(arguments);

}        //定位失败的回调)
Copy after login

(7)拖放API

  拖放是一种常见的特性,即抓取对象以后拖到另一个位置。在 HTML5 中,拖放是标准的一部分,任何元素都能够拖放。

  拖放的过程分为源对象和目标对象。源对象是指你即将拖动元素,而目标对象则是指拖动之后要放置的目标位置。

拖放的源对象(可能发生移动的)可以触发的事件——3个

dragstart:拖动开始

drag:拖动中

dragend:拖动结束

整个拖动过程的组成 dragstart*1 + drag*n + dragend*1

拖放目标对象(不会发生移动)可以触发的事件——4个

dragenter:拖动着进入

dragover:拖动着悬停

dragleave:拖动着离开

drop:释放

整个拖动过程的组成1: dragenter*1 + dragover*n + dragleave*1

整个拖动过程的组成2 dragenter*1 + dragover*n + drop*1

dataTransfer:用于数据传递的“拖拉机”对象;

拖动源对象事件中使用e.dataTransfer属性保存数据:

e.dataTransfer.setData( k, v )

拖动目标对象事件中使用e.dataTransfer属性读取数据:

var value = e.dataTransfer.getData( k )

(8)Web Worker

  当在 HTML 页面中执行脚本时,页面的状态是不可响应的,直到脚本已完成。

  web worker 是运行在后台的 JavaScript,独立于其他脚本,不会影响页面的性能。您可以继续做任何愿意做的事情:点击、选取内容等等,而此时 web worker 在后台运行。

  首先检测浏览器是否支持 Web Worker

 if(typeof(Worker)!=="undefined"){
   // 是的! Web worker 支持!
   // 一些代码.....
   }else{
   // //抱歉! Web Worker 不支持
   }
Copy after login

  下面的代码检测是否存在 worker,如果不存在,- 它会创建一个新的 web worker 对象,然后运行 "demo_workers.js" 中的代码

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

  然后我们就可以从 web worker 发送和接收消息了。向 web worker 添加一个 "onmessage" 事件监听器:

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

  当 web worker 传递消息时,会执行事件监听器中的代码。event.data 中存有来自 event.data 的数据。当我们创建 web worker 对象后,它会继续监听消息(即使在外部脚本完成之后)直到其被终止为止。

如需终止 web worker,并释放浏览器/计算机资源,使用 terminate() 方法。

完整的 Web Worker 实例代码

<!DOCTYPE html>
<html>
<body>

<p>Count numbers: <output id="result"></output></p>
<button onclick="startWorker()">Start Worker</button> 
<button onclick="stopWorker()">Stop Worker</button>
<br><br>

<script>var w;function startWorker()
{if(typeof(Worker)!=="undefined")
{  if(typeof(w)=="undefined")
    {
    w=new Worker("demo_workers.js");
    }
  w.onmessage = function (event) {
    document.getElementById("result").innerHTML=event.data;
  };
}else{
document.getElementById("result").innerHTML="Sorry, your browser does not support Web Workers...";
}
}function stopWorker()
{ 
w.terminate();
}</script>

</body>
</html>
Copy after login

  创建的计数脚本,该脚本存储于 "demo_workers.js" 文件中

var i=0; function timedCount()
 {
 i=i+1;
 postMessage(i);
 setTimeout("timedCount()",500);
 }

 timedCount();
Copy after login

(9)Web Storage

  使用HTML5可以在本地存储用户的浏览数据。早些时候,本地存储使用的是cookies。但是Web 存储需要更加的安全与快速. 这些数据不会被保存在服务器上,但是这些数据只用于用户请求网站数据上.它也可以存储大量的数据,而不影响网站的性能。数据以 键/值 对存在, web网页的数据只允许该网页访问使用。

客户端存储数据的两个对象为:

    • localStorage - 没有时间限制的数据存储
    • sessionStorage - 针对一个 session 的数据存储, 当用户关闭浏览器窗口后,数据会被删除。

  在使用 web 存储前,应检查浏览器是否支持 localStorage 和sessionStorage

if(typeof(Storage)!=="undefined")
   {   // 是的! 支持 localStorage  sessionStorage 对象!
   // 一些代码.....   } else
   {   // 抱歉! 不支持 web 存储。
   }
Copy after login

  不管是 localStorage,还是 sessionStorage,可使用的API都相同,常用的有如下几个(以localStorage为例):

    • 保存数据:localStorage.setItem(key,value);
    • 读取数据:localStorage.getItem(key);
    • 删除单个数据:localStorage.removeItem(key);
    • 删除所有数据:localStorage.clear();
    • 得到某个索引的key:localStorage.key(index);

(10)WebSocket

  WebSocket是HTML5开始提供的一种在单个 TCP 连接上进行全双工通讯的协议。在WebSocket API中,浏览器和服务器只需要做一个握手的动作,然后,浏览器和服务器之间就形成了一条快速通道。两者之间就直接可以数据互相传送。浏览器通过 JavaScript 向服务器发出建立 WebSocket 连接的请求,连接建立以后,客户端和服务器端就可以通过 TCP 连接直接交换数据。当你获取 Web Socket 连接后,你可以通过 send() 方法来向服务器发送数据,并通过 onmessage 事件来接收服务器返回的数据。

<!DOCTYPE HTML>
<html>
   <head>
   <meta charset="utf-8">
   <title>W3Cschool教程(w3cschool.cn)</title>
    
      <script type="text/javascript">         function WebSocketTest()
         {            if ("WebSocket" in window)
            {
               alert("您的浏览器支持 WebSocket!");               
               // 打开一个 web socket
               var ws = new WebSocket("ws://localhost:9998/echo");
                
               ws.onopen = function()
               {                  // Web Socket 已连接上,使用 send() 方法发送数据
                  ws.send("发送数据");
                  alert("数据发送中...");
               };
                
               ws.onmessage = function (evt) 
               { 
                  var received_msg = evt.data;
                  alert("数据已接收...");
               };
                
               ws.onclose = function()
               { 
                  // 关闭 websocket
                  alert("连接已关闭..."); 
               };
            }            
            else
            {               // 浏览器不支持 WebSocket
               alert("您的浏览器不支持 WebSocket!");
            }
         }      </script>
        
   </head>
   <body>
   
      <div id="sse">
         <a href="javascript:WebSocketTest()">运行 WebSocket</a>
      </div>
      
   </body>
</html>
Copy after login

更多编程相关知识,请访问:编程学习!!

The element specifies the option list of the input field
Use the list attribute of the element to bind the id of the element

Provides a reliable way to authenticate users
The tag specifies the key pair generation for the form device field.

For different types of output
such as calculations or scripts Output

The above is the detailed content of What are the new features of html5. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template