HTML5新增特性有哪些

91 阅读2分钟

一、语义化标签

新增了更具语义的 HTML 元素,提升页面结构和可访问性:

<!-- 结构标签 -->
<header>头部内容</header>
<nav>导航栏</nav>
<main>主内容</main>
<section>内容区块</section>
<article>独立文章</article>
<aside>侧边栏/附加内容</aside>
<footer>页脚</footer>

<!-- 文本语义标签 -->
<mark>高亮文本</mark>
<time datetime="2024-01-15">日期时间</time>
<figure>
  <img src="image.jpg" alt="示例">
  <figcaption>图片说明</figcaption>
</figure>
<details>
  <summary>展开/收起标题</summary>
  详细内容
</details>

二、多媒体支持

无需插件即可播放音视频:

<!-- 视频 -->
<video controls width="640">
  <source src="video.mp4" type="video/mp4">
  <source src="video.webm" type="video/webm">
  您的浏览器不支持 video 标签
</video>

<!-- 音频 -->
<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.ogg" type="audio/ogg">
</audio>

三、Canvas 绘图

提供 JavaScript 绘图 API:

<canvas id="myCanvas" width="500" height="300"></canvas>
<script>
  const canvas = document.getElementById('myCanvas');
  const ctx = canvas.getContext('2d');
  ctx.fillStyle = 'red';
  ctx.fillRect(10, 10, 100, 100);
</script>

四、SVG 支持

矢量图形支持:

<svg width="100" height="100">
  <circle cx="50" cy="50" r="40" fill="blue"/>
</svg>

五、表单增强

新增输入类型和属性:

<!-- 新输入类型 -->
<input type="email" placeholder="邮箱">
<input type="url" placeholder="网址">
<input type="number" min="1" max="10" step="1">
<input type="range" min="0" max="100">
<input type="date">
<input type="color">
<input type="search">

<!-- 新属性 -->
<input required>              <!-- 必填 -->
<input placeholder="提示">     <!-- 占位文本 -->
<input autofocus>            <!-- 自动聚焦 -->
<input pattern="[A-Za-z]{3}"><!-- 正则验证 -->
<datalist id="list">         <!-- 数据列表 -->
  <option value="选项1">
</datalist>
<input list="list">

六、本地存储

浏览器端数据存储:

// Web Storage
localStorage.setItem('key', 'value');  // 永久存储
sessionStorage.setItem('key', 'value'); // 会话存储

// Web SQL(已废弃)和 IndexedDB
// 更复杂的客户端数据库存储

七、Web Workers

多线程支持,避免阻塞 UI:

// main.js
const worker = new Worker('worker.js');
worker.postMessage('开始工作');
worker.onmessage = function(e) {
  console.log('收到结果:', e.data);
};

// worker.js
onmessage = function(e) {
  const result = e.data + '处理完成';
  postMessage(result);
};

八、WebSocket

全双工通信:

const socket = new WebSocket('ws://example.com');
socket.onopen = () => {
  socket.send('Hello Server!');
};
socket.onmessage = (event) => {
  console.log('收到消息:', event.data);
};

九、地理位置

获取用户位置:

if (navigator.geolocation) {
  navigator.geolocation.getCurrentPosition(
    (position) => {
      console.log('纬度:', position.coords.latitude);
      console.log('经度:', position.coords.longitude);
    },
    (error) => console.error('获取位置失败:', error)
  );
}

十、拖放 API

原生拖放支持:

<div draggable="true" id="dragElement">可拖拽元素</div>
<div id="dropZone">放置区域</div>

<script>
  dragElement.addEventListener('dragstart', (e) => {
    e.dataTransfer.setData('text/plain', '拖拽数据');
  });
  
  dropZone.addEventListener('dragover', (e) => {
    e.preventDefault(); // 允许放置
  });
  
  dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    const data = e.dataTransfer.getData('text/plain');
    dropZone.textContent = `收到: ${data}`;
  });
</script>

十一、其他重要特性

1. 离线应用

<!DOCTYPE html>
<html manifest="app.manifest">
<!-- manifest 文件定义缓存资源 -->

2. 历史管理

// pushState 和 replaceState
history.pushState({page: 1}, "title", "page1.html");
window.onpopstate = (event) => {
  console.log('状态变化:', event.state);
};

3. 页面可见性 API

document.addEventListener('visibilitychange', () => {
  if (document.hidden) {
    console.log('页面被隐藏');
  } else {
    console.log('页面可见');
  }
});

4. 全屏 API

// 进入全屏
element.requestFullscreen();

// 退出全屏
document.exitFullscreen();

5. 微数据(Microdata)

<div itemscope itemtype="http://schema.org/Person">
  <span itemprop="name">张三</span>
  <span itemprop="jobTitle">前端工程师</span>
</div>

十二、废弃的元素

HTML5 移除了一些表现性元素:

  • <font><center><big><strike>
  • <frame><frameset><noframes>
  • <acronym><applet><basefont><dir>

总结

类别主要特性
结构语义化标签、新的文档结构
媒体<audio>, <video>, <canvas>, SVG
表单新的输入类型、验证属性、数据列表
存储localStorage, sessionStorage, IndexedDB
通信WebSocket, Web Workers, Server-Sent Events
设备API地理位置、摄像头API、震动API等
图形Canvas 2D, WebGL, SVG
性能Web Workers, 应用缓存

HTML5 从单纯的标记语言演变为一个应用平台,提供了丰富的 API 和功能,支持构建复杂的 Web 应用。