HTML5 新特性

HTML5引入了许多新特性,包括新的语义化标签、表单控件、媒体标签和API,极大地增强了Web开发的能力。

新的表单控件

HTML5提供了更多类型的表单控件,提高了用户体验和数据验证能力。

html
<!-- 电子邮件输入 -->
<input type="email" placeholder="请输入邮箱">

<!-- URL输入 -->
<input type="url" placeholder="请输入网址">

<!-- 数字输入 -->
<input type="number" min="0" max="100" step="5">

<!-- 日期选择器 -->
<input type="date">

<!-- 颜色选择器 -->
<input type="color">

<!-- 搜索框 -->
<input type="search" placeholder="搜索">

<!-- 电话号码输入 -->
<input type="tel" placeholder="请输入电话号码">

<!-- 滑块控件 -->
<input type="range" min="0" max="100" value="50">

新的表单属性

HTML5引入了许多新的表单属性,用于增强表单验证和用户体验。

html
<!-- 自动完成 -->
<input type="text" autocomplete="on">

<!-- 必填项 -->
<input type="text" required>

<!-- 正则表达式验证 -->
<input type="text" pattern="[0-9]{3}-[0-9]{3}-[0-9]{4}" placeholder="xxx-xxx-xxxx">

<!-- 最小/最大值 -->
<input type="number" min="0" max="100">

<!-- 自动聚焦 -->
<input type="text" autofocus>

<!-- 占位符文本 -->
<input type="text" placeholder="请输入文本">

<!-- 只读 -->
<input type="text" value="只读内容" readonly>

<!-- 禁用 -->
<input type="text" value="禁用内容" disabled>

新的媒体标签

HTML5引入了原生的音频和视频标签,以及Canvas元素,使媒体处理更加便捷。

视频

html
<video controls width="640" height="360">
  <source src="video.mp4" type="video/mp4">
  <source src="video.webm" type="video/webm">
  您的浏览器不支持视频播放
</video>

音频

html
<audio controls>
  <source src="audio.mp3" type="audio/mpeg">
  <source src="audio.ogg" type="audio/ogg">
  您的浏览器不支持音频播放
</audio>

Canvas

Canvas元素用于通过JavaScript绘制图形、动画和其他视觉效果。

html
<canvas id="myCanvas" width="400" height="300"></canvas>
<script>
  var canvas = document.getElementById("myCanvas");
  var ctx = canvas.getContext("2d");
  
  // 绘制矩形
  ctx.fillStyle = "red";
  ctx.fillRect(10, 10, 100, 100);
  
  // 绘制圆形
  ctx.beginPath();
  ctx.arc(200, 150, 50, 0, Math.PI * 2);
  ctx.fillStyle = "blue";
  ctx.fill();
  ctx.closePath();
  
  // 绘制文本
  ctx.font = "30px Arial";
  ctx.fillStyle = "green";
  ctx.fillText("Hello Canvas", 10, 300);
</script>

新的API

HTML5还引入了许多新的API,用于增强Web应用的功能。

  • Geolocation API:获取用户地理位置
  • Local Storage API:本地存储数据
  • Drag and Drop API:拖放功能
  • Web Workers:后台运行JavaScript
  • WebSocket API:实时双向通信

示例:Geolocation API

html
<button onclick="getLocation()">获取我的位置</button>
<p id="location"></p>

<script>
function getLocation() {
  if (navigator.geolocation) {
    navigator.geolocation.getCurrentPosition(showPosition);
  } else {
    document.getElementById("location").innerHTML = "您的浏览器不支持地理定位。";
  }
}

function showPosition(position) {
  document.getElementById("location").innerHTML = 
    "纬度: " + position.coords.latitude + ", 经度: " + position.coords.longitude;
}
</script>
最后更新:2026-02-07