HTML5 & CSS3 Beginner's Guide (3) – New HTML5 Features

introduce

This article introduces some of the new features of HTML5. It mainly includes the following aspects:

  • web storage

  • Geographical location

  • drag and drop

  • server sent event

 

web storage

HTML5 Web Storage is designed and conceived to be a better mechanism for storing client-side web data. It is implemented through a web browser as a client-side database, which allows web pages to store data in the form of key-value pairs.

It has the following characteristics:

  • Each original website/domain can store up to 5MB of data.

  • You can use JavaScript to manipulate data in web storage through properties and methods to achieve access.

  • Just like cookies, you can choose to keep your data (maintain) even if you have left the website, closed your browser tab, exited your browser or turned off your computer.

  • Unlike cookies, which are created by server-side scripts, web storage is created by client-side scripts such as JavaScript.

  • Unlike cookies, data in web storage does not automatically accompany every HTTP request on the server side.

  • Web storage is natively supported in major web browsers such as Chrome, Opera, Firefox, Safari and IE8+. In other words, no third-party plugins are required.

NAS provides 2 different storage areas - session storage and local storage - which differ in scope and duration and need to be used in different situations.

 

session storage

Session storage, data is stored in the form of strings, which will only last in the current session. The data will be deleted when the browser window is closed. Session storage is specifically used when the same user is using the same website in different browsers doing multiple transactions at the same time. Transactions in each browser window get their own copy of the session store, which is distinct from another transaction in other browser windows. When the user closes the browser window, the session storage data attached to this window will continue to exist. In this way, transaction data is not leaked from one browser window to another. Session storage is the definitive solution for cookies, as stated in  the HTML5 Web Storage Specification  :

Quote:

"If a user purchases an airplane ticket in two different windows using the same site. If the site uses cookies to track the ticket the user has purchased, when the user clicks from both windows, the ticket currently being purchased will be "Leaks" from one window to another, potentially causing users to buy two tickets for the same flight without realizing it.

Session storage must be used for network activity that handles confidential and sensitive information, such as credit card numbers, social security numbers, and login credentials. This information is vulnerable to "DNS spoofing" and should not be stored for more than a single session. "

How to create and access a sessionStorage:

<script type="text/javascript">

sessionStorage.lastname="Smith";

document.write(sessionStorage.lastname);

</script>

 

local storage

Local storage, the data is stored as a string and will persist (unless you explicitly delete it). The data persists even if the browser window is closed, and is available if subsequent visits to the same origin use the same browser. Local storage is designed for storing data that spans multiple browser windows and lasts longer than the current session.

不像桌面系统,Web 应用程序一直缺乏离线工作的能力。现在不一样了,HTML5 本地存储的出现,已经使脱机工作成为了可能。试想一下你正在填写一份多页的 Web 表单,或者撰写一篇文章时,截止日期已经迫在眉睫,突然发生网络故障中断。你将会失去你精心创建的所有数据。因为有了本地存储,你就可以继续离线工作,而 Web 应用程序会使用一些客户端脚本如 JavaScript 间歇性地将你的工作保存到本地存储。

一个网站可以让用户自定义网页的主题和布局,并在本地存储中保存这些设置。以这种方式,用户可以在后续访问中看到自己个人的网页。

如何创建和访问 localStorage:

<script type="text/javascript">

localStorage.lastname="Smith";

document.write(localStorage.lastname);

</script>

 

地理定位

HTML geolocation API 只有一个对象,就是 navigator.geolocation 对象。你可以将 navigator.geolocation 比作浏览器中的指南针。浏览器是否支持这个 API,还有待确认。你可以通过将以下的 if-else 写入到自己的代码中,来检测浏览器是否支持。

// Check whether browser supports Geolocation API or not
if (navigator.geolocation) // Supported
{
    // place the geolocation code here
}
else // Not supported
{
    alert("Oop! This browser does not support HTML5 Geolocation.");
}

navigator.geolocation 对象公开了3中方法 getCurrentPosition(),watchPosition(),和clearWatch()。

  • getCurrentPosition()

getCurrentPosition()方法用来获得用户的当前位置。

navigator.geolocation.getCurrentPosition(getPosition);
  • watchPosition()

watchPosition()方法与 getCurrentPosition()方法是几乎相同的。它们都返回当前位置信息并具有相同的方法签名 - 一个成功的回调函数,一个错误的回调函数和一个位置选项对象。唯一的区别在于, 一旦激活了点击按钮,getCurrentPosition()方法会返回位置信息;而 watchPosition()方法将继续获得位置信息,一旦用户设备的位置发生变化并在初始话激活之后。

该 watchPosition()方法会返回一个 watch ID,当不再需要获取位置时,可以用 watch ID 来停止 watchPositon()方法。

  • clearWatch()

clearWatch()方法以 watchPosition()方法的 watch ID 作为参数,用于停止执行 watchPosition()方法。

 

拖放

我们已经很熟悉拖放电脑桌面上的文件、文件夹和图标了。拖放是一种任何的桌面应用具有的强有力的也是理所当然应该具备的用户交互。使用像鼠标这样的指针设备,通过拖放来实现拷贝,插入和删除任何电脑桌面上的文件和对象。

HTML5 Drag and Drop API 提供了对浏览器拖放操作原生的支持,使得代码实现拖放变得更容易。

  • 设置元素为可拖放

首先,为了使元素可拖动,把 draggable 属性设置为 true :

<img draggable="true" />

  • 拖动什么

然后,规定当元素被拖动时,会发生什么。

在上面的例子中,ondragstart 属性调用了一个函数,drag(event),它规定了被拖动的数据。

dataTransfer.setData( ) 方法设置被拖数据的数据类型和值:

function drag(ev)
{
    ev.dataTransfer.setData("Text",ev.target.id);
}
  • 放到何处

ondragover 事件规定在何处放置被拖动的数据。

默认地,无法将数据/元素放置到其他元素中。如果需要设置允许放置,我们必须阻止对元素的默认处理方式。

这要通过调用 ondragover 事件的 event.preventDefault() 方法:

event.preventDefault()
  • 进行放置

当放置被拖数据时,会发生 drop 事件。

在上面的例子中,ondrop 属性调用了一个函数,drop(event):

function drop(ev)
{
    ev.preventDefault();
    var data=ev.dataTransfer.getData("Text");
    ev.target.appendChild(document.getElementById(data));
}

 

服务器发送事件

传统的用户和网站之间的交互模式是用户发起的请求和应答类型。用户通过浏览器主动发起请求,并且等待服务器的应答。为了检查某个特定的网页上是否有更新,用户需要通过点击浏览器上更新/重新登录按钮来向服务器发送新的请求。换言之,服务器必须不间断的将服务器侧的更新推送出去。当信息不间断的无法预测的变化时,通过这种方式来获取一些关键的做决定的信息,就不是特别有用了。例如股票价格更新,新闻传递,天气预报等。

当信息到达时,HTML 服务器发送事件(SSE)使得服务器能够将信息发送(推送)到客户端,避免了服务器持续推送的需要。这也使得网站在不需要任何第三方插件的情况下,能够为客户端提供推送服务。

  • Server-Sent 事件 - 单向消息传递

Server-Sent 事件指的是网页自动获取来自服务器的更新。

以前也可能做到这一点,前提是网页不得不询问是否有可用的更新。通过服务器发送事件,更新能够自动到达。

  • 接收 Server-Sent 事件通知

EventSource 对象用于接收服务器发送事件通知:

var source=new EventSource("demo_sse.php");
source.onmessage=function(event)
{
   document.getElementById("result").innerHTML+=event.data + "<br />";
};

代码解释:  

  • 创建一个新的 EventSource 对象,然后规定发送更新的页面的 URL(本例中是 "demo_sse.php")
  • 每接收到一次更新,就会发生 onmessage 事件
  • 当 onmessage 事件发生时,把已接收的数据推入 id 为 "result" 的元素中

 

  • 检测 Server-Sent 事件支持

在上面的 TIY 实例中,我们编写了一段额外的代码来检测服务器发送事件的浏览器支持情况:

if(typeof(EventSource)!=="undefined")
{
   // Yes! Server-sent events support!
   // Some code.....
}
else
{
    // Sorry! No server-sent events support..
}
  • 服务器端代码实例

为了让上面的例子可以运行,您还需要能够发送数据更新的服务器(比如 PHP 和 ASP)。

服务器端事件流的语法是非常简单的。把 "Content-Type" 报头设置为 "text/event-stream"。现在,您可以开始发送事件流了。

PHP 代码 (demo_sse.php):

<?php
header('Content-Type: text/event-stream');
header('Cache-Control: no-cache');

$time = date('r');
echo "data: The server time is: {$time}\n\n";
flush();
?>

ASP 代码 (VB) (demo_sse.asp):

<%
Response.ContentType="text/event-stream"
Response.Expires=-1
Response.Write("data: " & now())
Response.Flush()
%>

代码解释:

  • 把报头 "Content-Type" 设置为 "text/event-stream"
  • 规定不对页面进行缓存
  • 输出发送日期(始终以 "data: " 开头)
  • 向网页刷新输出数据

总结

本文介绍的 HTML5 一些新特性就到这里,在后面一篇文章中,我们将会学习到 HTML5 的 Canvas 知识。。学习了 HTML5 的新特性,能够帮助我们在进行前端开发时更加顺利,同时也可以借助一些前端开发工具。Wijmo 是一款大而全面的前端 HTML5 / JavaScript UI控件集,能为企业应用提供更加灵活的操作体验,现已全面支持Angular 2。

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=327038790&siteId=291194637