HTML5新特性

HTML5新特性概述

HTML5是HTML的最新版本,引入了许多新的语义化标签、API和特性,使Web开发更加强大和灵活。

东巴文(db-w.cn) 认为:HTML5不仅是一个标记语言,更是一个完整的Web应用开发平台。

新语义化标签

HTML5引入了大量语义化标签,使网页结构更加清晰。

文档结构标签

标签 说明 用途
<header> 页眉 文档或章节的头部
<nav> 导航 导航链接区域
<main> 主内容 文档的主要内容
<article> 文章 独立完整的内容
<section> 章节 主题分组的内容
<aside> 附属内容 侧边栏或相关内容
<footer> 页脚 文档或章节的底部

示例

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5语义化标签示例</title>
</head>
<body>
    <header>
        <h1>网站标题</h1>
        <nav>
            <ul>
                <li><a href="/">首页</a></li>
                <li><a href="/about">关于</a></li>
            </ul>
        </nav>
    </header>
    
    <main>
        <article>
            <h2>文章标题</h2>
            <p>文章内容...</p>
        </article>
    </main>
    
    <aside>
        <h3>侧边栏</h3>
        <p>相关内容...</p>
    </aside>
    
    <footer>
        <p>版权信息</p>
    </footer>
</body>
</html>

东巴文点评:语义化标签让代码结构清晰,对SEO和可访问性都有很大帮助。

新表单特性

新输入类型

HTML5新增了多种输入类型,使表单更加强大。

类型 说明 示例
email 邮箱地址 <input type="email">
url URL地址 <input type="url">
tel 电话号码 <input type="tel">
number 数字 <input type="number">
range 滑块 <input type="range">
date 日期 <input type="date">
time 时间 <input type="time">
datetime-local 日期时间 <input type="datetime-local">
month 月份 <input type="month">
week <input type="week">
color 颜色 <input type="color">
search 搜索 <input type="search">

示例

<form>
    <!-- 邮箱 -->
    <label for="email">邮箱:</label>
    <input type="email" id="email" name="email" required>
    
    <!-- 数字 -->
    <label for="age">年龄:</label>
    <input type="number" id="age" name="age" min="1" max="120">
    
    <!-- 日期 -->
    <label for="birthday">生日:</label>
    <input type="date" id="birthday" name="birthday">
    
    <!-- 颜色 -->
    <label for="color">颜色:</label>
    <input type="color" id="color" name="color" value="#ff0000">
    
    <!-- 范围 -->
    <label for="volume">音量:</label>
    <input type="range" id="volume" name="volume" min="0" max="100">
    
    <button type="submit">提交</button>
</form>

新表单属性

属性 说明 适用元素
placeholder 占位文本 input, textarea
required 必填字段 input, select, textarea
pattern 正则验证 input
autofocus 自动聚焦 input, select, textarea
autocomplete 自动完成 form, input
novalidate 禁用验证 form
formnovalidate 禁用验证 button, input
multiple 多选 input, select
list 关联datalist input

东巴文点评:HTML5表单特性大大减少了JavaScript验证的工作量。

新多媒体标签

audio标签

<audio>标签用于嵌入音频内容。

<!-- 基本用法 -->
<audio src="music.mp3" controls></audio>

<!-- 多格式支持 -->
<audio controls>
    <source src="music.mp3" type="audio/mpeg">
    <source src="music.ogg" type="audio/ogg">
    您的浏览器不支持audio标签。
</audio>

<!-- 属性示例 -->
<audio 
    src="music.mp3" 
    controls 
    autoplay 
    loop 
    muted 
    preload="auto">
</audio>

audio属性

属性 说明
src 音频文件路径
controls 显示控制面板
autoplay 自动播放
loop 循环播放
muted 静音
preload 预加载策略(auto/metadata/none)

video标签

<video>标签用于嵌入视频内容。

<!-- 基本用法 -->
<video src="video.mp4" controls></video>

<!-- 多格式支持 -->
<video controls width="640" height="360">
    <source src="video.mp4" type="video/mp4">
    <source src="video.webm" type="video/webm">
    您的浏览器不支持video标签。
</video>

<!-- 属性示例 -->
<video 
    src="video.mp4" 
    controls 
    autoplay 
    loop 
    muted 
    poster="poster.jpg"
    width="640" 
    height="360"
    preload="auto">
</video>

video属性

属性 说明
src 视频文件路径
controls 显示控制面板
autoplay 自动播放
loop 循环播放
muted 静音
poster 封面图片
width 宽度
height 高度
preload 预加载策略

东巴文点评:HTML5多媒体标签让网页可以轻松嵌入音视频,无需Flash插件。

Canvas绘图

基本用法

<canvas>标签用于通过JavaScript绘制图形。

<canvas id="myCanvas" width="400" height="300">
    您的浏览器不支持canvas标签。
</canvas>

<script>
    const canvas = document.getElementById('myCanvas');
    const ctx = canvas.getContext('2d');
    
    // 绘制矩形
    ctx.fillStyle = 'red';
    ctx.fillRect(10, 10, 100, 50);
    
    // 绘制圆形
    ctx.beginPath();
    ctx.arc(200, 100, 50, 0, Math.PI * 2);
    ctx.fillStyle = 'blue';
    ctx.fill();
    
    // 绘制线条
    ctx.beginPath();
    ctx.moveTo(10, 200);
    ctx.lineTo(390, 200);
    ctx.strokeStyle = 'green';
    ctx.lineWidth = 2;
    ctx.stroke();
    
    // 绘制文本
    ctx.font = '20px Arial';
    ctx.fillStyle = 'black';
    ctx.fillText('东巴文Canvas', 150, 250);
</script>

绘图方法

方法 说明
fillRect() 填充矩形
strokeRect() 描边矩形
clearRect() 清除矩形
beginPath() 开始路径
moveTo() 移动到点
lineTo() 连线到点
arc() 绘制圆弧
fill() 填充
stroke() 描边
drawImage() 绘制图像

东巴文点评:Canvas为Web提供了强大的绘图能力,可以创建图表、游戏、动画等。

SVG内联

HTML5支持直接在HTML中嵌入SVG。

基本形状

<svg width="400" height="300">
    <!-- 矩形 -->
    <rect x="10" y="10" width="100" height="50" fill="red"/>
    
    <!-- 圆形 -->
    <circle cx="200" cy="100" r="50" fill="blue"/>
    
    <!-- 椭圆 -->
    <ellipse cx="300" cy="100" rx="70" ry="40" fill="green"/>
    
    <!-- 线条 -->
    <line x1="10" y1="200" x2="390" y2="200" stroke="black" stroke-width="2"/>
    
    <!-- 多边形 -->
    <polygon points="200,250 250,300 150,300" fill="orange"/>
    
    <!-- 文本 -->
    <text x="200" y="150" text-anchor="middle" fill="purple" font-size="20">
        东巴文SVG
    </text>
</svg>

渐变和滤镜

<svg width="400" height="300">
    <!-- 渐变定义 -->
    <defs>
        <linearGradient id="grad1" x1="0%" y1="0%" x2="100%" y2="0%">
            <stop offset="0%" style="stop-color:rgb(255,255,0);stop-opacity:1" />
            <stop offset="100%" style="stop-color:rgb(255,0,0);stop-opacity:1" />
        </linearGradient>
        
        <filter id="shadow">
            <feDropShadow dx="5" dy="5" stdDeviation="3"/>
        </filter>
    </defs>
    
    <!-- 使用渐变 -->
    <rect x="50" y="50" width="300" height="100" fill="url(#grad1)"/>
    
    <!-- 使用滤镜 -->
    <circle cx="200" cy="200" r="50" fill="blue" filter="url(#shadow)"/>
</svg>

东巴文点评:SVG是矢量图形,可以无限缩放而不失真,适合图标、图表等场景。

地理定位API

HTML5提供了地理定位API,可以获取用户的地理位置。

基本用法

// 检查浏览器支持
if ('geolocation' in navigator) {
    // 获取当前位置
    navigator.geolocation.getCurrentPosition(
        // 成功回调
        function(position) {
            console.log('纬度:' + position.coords.latitude);
            console.log('经度:' + position.coords.longitude);
            console.log('精度:' + position.coords.accuracy);
        },
        // 错误回调
        function(error) {
            console.error('获取位置失败:' + error.message);
        },
        // 选项
        {
            enableHighAccuracy: true,  // 高精度
            timeout: 5000,             // 超时时间
            maximumAge: 0              // 不使用缓存位置
        }
    );
} else {
    console.log('浏览器不支持地理定位');
}

持续监听位置

// 监听位置变化
const watchId = navigator.geolocation.watchPosition(
    function(position) {
        console.log('新位置:', position.coords);
    },
    function(error) {
        console.error('监听失败:', error);
    }
);

// 停止监听
navigator.geolocation.clearWatch(watchId);

东巴文点评:地理定位API需要用户授权,适合地图应用、本地服务等场景。

本地存储

HTML5提供了本地存储API,可以在浏览器中存储数据。

localStorage

localStorage用于持久化存储数据,没有过期时间。

// 存储数据
localStorage.setItem('username', '张三');
localStorage.setItem('age', '25');

// 读取数据
const username = localStorage.getItem('username');
const age = localStorage.getItem('age');

// 删除数据
localStorage.removeItem('username');

// 清空所有数据
localStorage.clear();

// 存储对象
const user = {
    name: '张三',
    age: 25,
    email: 'zhangsan@example.com'
};
localStorage.setItem('user', JSON.stringify(user));

// 读取对象
const savedUser = JSON.parse(localStorage.getItem('user'));

sessionStorage

sessionStorage用于会话存储,关闭浏览器后数据会被清除。

// 存储数据
sessionStorage.setItem('token', 'abc123');

// 读取数据
const token = sessionStorage.getItem('token');

// 删除数据
sessionStorage.removeItem('token');

// 清空所有数据
sessionStorage.clear();

localStorage vs sessionStorage

特性 localStorage sessionStorage
生命周期 永久 会话期间
存储大小 约5MB 约5MB
作用域 同源窗口共享 仅当前窗口
使用场景 用户设置、主题 临时数据、表单数据

东巴文点评:本地存储是Web应用的重要特性,可以保存用户设置、离线数据等。

Web Workers

Web Workers允许在后台线程中运行JavaScript,不阻塞主线程。

基本用法

// 主线程
const worker = new Worker('worker.js');

// 发送消息给Worker
worker.postMessage({ num: 10000000 });

// 接收Worker的消息
worker.onmessage = function(e) {
    console.log('计算结果:', e.data);
};

// 错误处理
worker.onerror = function(e) {
    console.error('Worker错误:', e.message);
};

// 终止Worker
worker.terminate();
// worker.js
// 接收主线程消息
self.onmessage = function(e) {
    const num = e.data.num;
    
    // 执行耗时计算
    let result = 0;
    for (let i = 0; i < num; i++) {
        result += i;
    }
    
    // 发送结果回主线程
    self.postMessage(result);
};

东巴文点评:Web Workers适合执行耗时计算、数据处理等任务,避免阻塞主线程。

WebSockets

WebSockets提供了全双工通信通道,适合实时应用。

基本用法

// 创建WebSocket连接
const socket = new WebSocket('wss://example.com/ws');

// 连接打开
socket.onopen = function(e) {
    console.log('连接已建立');
    socket.send('Hello Server!');
};

// 接收消息
socket.onmessage = function(e) {
    console.log('收到消息:', e.data);
};

// 连接关闭
socket.onclose = function(e) {
    console.log('连接已关闭');
};

// 错误处理
socket.onerror = function(e) {
    console.error('WebSocket错误:', e);
};

// 发送消息
socket.send('Hello World!');

// 关闭连接
socket.close();

东巴文点评:WebSockets适合聊天应用、实时通知、在线协作等场景。

拖放API

HTML5提供了原生拖放API,可以实现元素的拖放功能。

基本用法

<div id="draggable" draggable="true">
    拖动我
</div>

<div id="droppable">
    放到这里
</div>

<script>
    const draggable = document.getElementById('draggable');
    const droppable = document.getElementById('droppable');
    
    // 拖动开始
    draggable.addEventListener('dragstart', function(e) {
        e.dataTransfer.setData('text/plain', e.target.id);
    });
    
    // 拖动经过
    droppable.addEventListener('dragover', function(e) {
        e.preventDefault();
    });
    
    // 放下
    droppable.addEventListener('drop', function(e) {
        e.preventDefault();
        const id = e.dataTransfer.getData('text/plain');
        const element = document.getElementById(id);
        e.target.appendChild(element);
    });
</script>

拖放事件

事件 说明
dragstart 拖动开始
drag 拖动中
dragend 拖动结束
dragenter 拖动进入目标
dragover 拖动在目标上方
dragleave 拖动离开目标
drop 放下

东巴文点评:拖放API可以创建直观的用户界面,如文件上传、任务管理等。

学习检验

知识点测试

问题1:以下哪个是HTML5新增的输入类型?

A. text B. password C. email D. checkbox

<details> <summary>点击查看答案</summary>

答案:C

东巴文解释email是HTML5新增的输入类型,用于邮箱地址输入。textpasswordcheckbox都是HTML4就有的类型。

</details>

问题2:以下哪个标签用于定义独立的、完整的内容块?

A. <section> B. <article> C. <aside> D. <div>

<details> <summary>点击查看答案</summary>

答案:B

东巴文解释<article>标签用于定义独立的、完整的内容块。<section>用于主题分组,<aside>用于附属内容,<div>没有语义。

</details>

实践任务

任务:创建一个HTML5页面,包含以下特性:

  1. 使用语义化标签(header、nav、main、article、footer)
  2. 使用新的表单输入类型(email、date、color)
  3. 嵌入一个视频播放器
<details> <summary>点击查看参考答案</summary>
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>HTML5新特性示例 - 东巴文</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            line-height: 1.6;
            color: #333;
        }
        
        header {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            padding: 1rem 0;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
        }
        
        header .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        
        header h1 {
            font-size: 24px;
        }
        
        nav ul {
            list-style: none;
            display: flex;
            gap: 20px;
        }
        
        nav a {
            color: white;
            text-decoration: none;
            transition: opacity 0.3s;
        }
        
        nav a:hover {
            opacity: 0.8;
        }
        
        main {
            max-width: 1200px;
            margin: 0 auto;
            padding: 40px 20px;
        }
        
        article {
            background: white;
            padding: 30px;
            border-radius: 8px;
            box-shadow: 0 2px 10px rgba(0,0,0,0.1);
            margin-bottom: 30px;
        }
        
        h2 {
            color: #667eea;
            margin-bottom: 20px;
        }
        
        form {
            display: grid;
            gap: 20px;
        }
        
        .form-group {
            display: grid;
            gap: 8px;
        }
        
        label {
            font-weight: 600;
            color: #555;
        }
        
        input {
            padding: 12px;
            border: 2px solid #e0e0e0;
            border-radius: 5px;
            font-size: 16px;
            transition: border-color 0.3s;
        }
        
        input:focus {
            outline: none;
            border-color: #667eea;
        }
        
        button {
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            color: white;
            border: none;
            padding: 12px 30px;
            border-radius: 5px;
            font-size: 16px;
            cursor: pointer;
            transition: transform 0.3s;
        }
        
        button:hover {
            transform: translateY(-2px);
        }
        
        video {
            width: 100%;
            border-radius: 8px;
        }
        
        footer {
            background: #333;
            color: white;
            text-align: center;
            padding: 20px;
            margin-top: 40px;
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <h1>东巴文学习平台</h1>
            <nav>
                <ul>
                    <li><a href="/">首页</a></li>
                    <li><a href="/courses">课程</a></li>
                    <li><a href="/about">关于</a></li>
                </ul>
            </nav>
        </div>
    </header>
    
    <main>
        <article>
            <h2>HTML5表单示例</h2>
            <form>
                <div class="form-group">
                    <label for="email">邮箱:</label>
                    <input type="email" id="email" name="email" placeholder="请输入邮箱" required>
                </div>
                
                <div class="form-group">
                    <label for="birthday">生日:</label>
                    <input type="date" id="birthday" name="birthday">
                </div>
                
                <div class="form-group">
                    <label for="color">喜欢的颜色:</label>
                    <input type="color" id="color" name="color" value="#667eea">
                </div>
                
                <button type="submit">提交</button>
            </form>
        </article>
        
        <article>
            <h2>HTML5视频播放器</h2>
            <video controls poster="poster.jpg">
                <source src="video.mp4" type="video/mp4">
                <source src="video.webm" type="video/webm">
                您的浏览器不支持video标签。
            </video>
        </article>
    </main>
    
    <footer>
        <p>&copy; 2024 东巴文学习平台. 保留所有权利.</p>
    </footer>
</body>
</html>
</details>

东巴文(db-w.cn) - 让编程学习更有趣、更高效!