HTML5 基础学习笔记详细版

HTML5 是超文本标记语言(HyperText Markup Language)的第五个主要版本,它不仅是一个标记语言,更是一个构建现代 Web 应用的基础平台。HTML5 引入了许多新特性,包括语义化标签、多媒体支持、本地存储、图形绘制等。


1. HTML5 基础结构

1.1 标准文档结构

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta name="description" content="HTML5基础学习笔记">
    <meta name="keywords" content="HTML5, 学习笔记, Web开发">
    <title>HTML5 基础学习笔记</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <!-- 页面内容 -->
    <script src="script.js"></script>
</body>
</html>

关键点说明:

  • <!DOCTYPE html>:声明文档类型为 HTML5
  • <html lang="zh-CN">:指定页面语言为简体中文
  • <meta charset="UTF-8">:设置字符编码为 UTF-8
  • <meta name="viewport">:响应式设计的关键,控制视口缩放

2. 语义化标签(Semantic Elements)

HTML5 引入了大量语义化标签,使代码更易读、更利于 SEO 和辅助技术。

2.1 页面结构标签

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>语义化标签示例</title>
</head>
<body>
    <!-- 页眉 -->
    <header>
        <h1>我的网站</h1>
        <nav>
            <ul>
                <li><a href="#home">首页</a></li>
                <li><a href="#about">关于</a></li>
                <li><a href="#contact">联系</a></li>
            </ul>
        </nav>
    </header>

    <!-- 主体内容 -->
    <main>
        <!-- 文章区域 -->
        <article>
            <h2>HTML5 新特性</h2>
            <p>HTML5 引入了许多新标签和 API...</p>
            
            <!-- 文章内的独立部分 -->
            <section>
                <h3>语义化标签</h3>
                <p>语义化标签让代码结构更清晰。</p>
            </section>
            
            <!-- 侧边栏 -->
            <aside>
                <h4>相关文章</h4>
                <ul>
                    <li><a href="#">CSS3 教程</a></li>
                    <li><a href="#">JavaScript 基础</a></li>
                </ul>
            </aside>
        </article>
        
        <!-- 另一个文章 -->
        <article>
            <h2>Web 开发趋势</h2>
            <p>现代 Web 开发越来越注重用户体验...</p>
        </article>
    </main>

    <!-- 页脚 -->
    <footer>
        <p>&copy; 2024 我的网站. 保留所有权利。</p>
        <address>
            联系邮箱:<a href="mailto:info@example.com">info@example.com</a>
        </address>
    </footer>
</body>
</html>

2.2 语义化标签对照表

标签 用途 替代方案(HTML4)
<header> 页面或区域的页眉 <div class="header">
<nav> 导航链接区域 <div class="nav">
<main> 页面主要内容 <div id="main">
<article> 独立的内容块(如博客文章) <div class="article">
<section> 文档中的主题区块 <div class="section">
<aside> 侧边栏或相关内容 <div class="sidebar">
<footer> 页面或区域的页脚 <div class="footer">
<figure> 图片、图表等媒体内容 <div class="figure">
<figcaption> <figure> 的标题 <div class="caption">
<time> 时间或日期 <span class="time">
<mark> 高亮文本 <span class="highlight">

3. 表单增强(Forms)

HTML5 大幅增强了表单功能,提供了更多输入类型和验证属性。

3.1 新输入类型

<form action="/submit" method="post">
    <!-- 邮箱输入 -->
    <label for="email">邮箱:</label>
    <input type="email" id="email" name="email" required>
    
    <!-- URL输入 -->
    <label for="website">网站:</label>
    <input type="url" id="website" name="website">
    
    <!-- 数字输入 -->
    <label for="age">年龄:</label>
    <input type="number" id="age" name="age" min="1" max="120" step="1">
    
    <!-- 日期选择 -->
    <label for="birthday">生日:</label>
    <input type="date" id="birthday" name="birthday">
    
    <!-- 时间选择 -->
    <label for="meeting">会议时间:</label>
    <input type="time" id="meeting" name="meeting">
    
    <!-- 日期时间选择 -->
    <label for="event">活动时间:</label>
    <input type="datetime-local" id="event" name="event">
    
    <!-- 范围滑块 -->
    <label for="volume">音量:</label>
    <input type="range" id="volume" name="volume" min="0" max="100" value="50">
    
    <!-- 搜索框 -->
    <label for="search">搜索:</label>
    <input type="search" id="search" name="search">
    
    <!-- 颜色选择器 -->
    <label for="color">选择颜色:</label>
    <input type="color" id="color" name="color" value="#ff0000">
    
    <!-- 电话输入 -->
    <label for="phone">电话:</label>
    <input type="tel" id="phone" name="phone" pattern="[0-9]{11}">
    
    <button type="submit">提交</button>
</form>

3.2 表单验证属性

<form>
    <!-- 必填字段 -->
    <input type="text" required placeholder="必填项">
    
    <!-- 最小/最大值 -->
    <input type="number" min="0" max="100" value="50">
    
    <!-- 正则表达式验证 -->
    <input type="text" pattern="[A-Za-z]{3}" title="请输入3个字母">
    
    <!-- 默认值 -->
    <input type="text" value="默认文本">
    
    <!-- 占位符 -->
    <input type="text" placeholder="请输入内容">
    
    <!-- 自动完成 -->
    <input type="text" autocomplete="on">
    
    <!-- 禁用自动完成 -->
    <input type="password" autocomplete="off">
    
    <!-- 只读字段 -->
    <input type="text" value="只读内容" readonly>
    
    <!-- 禁用字段 -->
    <input type="text" value="禁用内容" disabled>
    
    <!-- 自动聚焦 -->
    <input type="text" autofocus>
    
    <!-- 多文件上传 -->
    <input type="file" multiple>
    
    <!-- 自动建议 -->
    <input type="text" list="browsers">
    <datalist id="browsers">
        <option value="Chrome">
        <option value="Firefox">
        <option value="Safari">
        <option value="Edge">
    </datalist>
</form>

4. 多媒体支持

HTML5 原生支持音频和视频,无需插件。

4.1 音频播放

<!-- 基本音频 -->
<audio controls>
    <source src="audio.mp3" type="audio/mpeg">
    <source src="audio.ogg" type="audio/ogg">
    您的浏览器不支持 audio 元素。
</audio>

<!-- 带预加载和自动播放 -->
<audio controls preload="auto" autoplay loop>
    <source src="music.mp3" type="audio/mpeg">
</audio>

<!-- 自定义控制(需要JavaScript) -->
<audio id="myAudio" controls>
    <source src="song.mp3" type="audio/mpeg">
</audio>
<button onclick="document.getElementById('myAudio').play()">播放</button>
<button onclick="document.getElementById('myAudio').pause()">暂停</button>

4.2 视频播放

<!-- 基本视频 -->
<video width="640" height="360" controls poster="thumbnail.jpg">
    <source src="movie.mp4" type="video/mp4">
    <source src="movie.webm" type="video/webm">
    <source src="movie.ogv" type="video/ogg">
    您的浏览器不支持 video 元素。
</video>

<!-- 视频属性 -->
<video 
    width="640" 
    height="360" 
    controls 
    preload="metadata"
    muted
    poster="preview.jpg">
    <source src="video.mp4" type="video/mp4">
</video>

<!-- 全屏视频 -->
<video width="100%" controls>
    <source src="fullvideo.mp4" type="video/mp4">
</video>

4.3 媒体事件(JavaScript控制)

const video = document.querySelector('video');

video.addEventListener('play', () => {
    console.log('视频开始播放');
});

video.addEventListener('pause', () => {
    console.log('视频暂停');
});

video.addEventListener('ended', () => {
    console.log('视频播放结束');
});

video.addEventListener('timeupdate', () => {
    console.log('当前时间:', video.currentTime);
});

// 控制方法
video.play();
video.pause();
video.currentTime = 30; // 跳转到30秒
video.volume = 0.5; // 设置音量

5. 图形绘制(Canvas & SVG)

5.1 Canvas 绘图

<canvas id="myCanvas" width="400" height="300" style="border:1px solid #ccc;"></canvas>

<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// 绘制矩形
ctx.fillStyle = '#FF6347';
ctx.fillRect(50, 50, 100, 80);

// 绘制边框矩形
ctx.strokeStyle = '#4682B4';
ctx.lineWidth = 3;
ctx.strokeRect(200, 50, 100, 80);

// 绘制圆形
ctx.beginPath();
ctx.arc(100, 200, 40, 0, Math.PI * 2);
ctx.fillStyle = '#32CD32';
ctx.fill();

// 绘制线条
ctx.beginPath();
ctx.moveTo(200, 200);
ctx.lineTo(300, 250);
ctx.lineTo(350, 150);
ctx.strokeStyle = '#FF1493';
ctx.lineWidth = 5;
ctx.stroke();

// 绘制文本
ctx.font = '24px Arial';
ctx.fillStyle = '#000080';
ctx.fillText('Hello Canvas', 150, 280);

// 绘制渐变
const gradient = ctx.createLinearGradient(0, 0, 400, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(0.5, 'yellow');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(50, 150, 300, 50);
</script>

5.2 SVG 矢量图形

<svg width="400" height="300" xmlns="http://www.w3.org/2000/svg">
    <!-- 矩形 -->
    <rect x="10" y="10" width="100" height="80" fill="tomato" stroke="black" stroke-width="2"/>
    
    <!-- 圆形 -->
    <circle cx="200" cy="50" r="40" fill="lightblue" stroke="navy" stroke-width="3"/>
    
    <!-- 椭圆 -->
    <ellipse cx="300" cy="50" rx="60" ry="30" fill="lightgreen" stroke="green" stroke-width="2"/>
    
    <!-- 线条 -->
    <line x1="10" y1="150" x2="150" y2="250" stroke="purple" stroke-width="4"/>
    
    <!-- 多边形 -->
    <polygon points="200,150 250,250 150,250" fill="orange" stroke="darkorange" stroke-width="2"/>
    
    <!-- 路径 -->
    <path d="M 300 150 Q 350 100 400 150 T 500 150" 
          fill="none" 
          stroke="red" 
          stroke-width="3"/>
    
    <!-- 文本 -->
    <text x="10" y="280" font-family="Arial" font-size="20" fill="black">
        SVG 文本示例
    </text>
    
    <!-- 渐变 -->
    <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>
    </defs>
    <rect x="10" y="10" width="100" height="80" fill="url(#grad1)" />
</svg>

6. 本地存储(Local Storage & Session Storage)

6.1 Local Storage(持久化存储)

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

// 读取数据
const name = localStorage.getItem('username');
console.log(name); // 输出:张三

// 删除单个数据
localStorage.removeItem('age');

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

// 存储对象(需要序列化)
const user = {
    name: '李四',
    age: 30,
    email: 'lisi@example.com'
};
localStorage.setItem('user', JSON.stringify(user));

// 读取对象
const userData = JSON.parse(localStorage.getItem('user'));
console.log(userData.name); // 输出:李四

// 遍历所有存储
for (let i = 0; i < localStorage.length; i++) {
    const key = localStorage.key(i);
    const value = localStorage.getItem(key);
    console.log(`${key}: ${value}`);
}

6.2 Session Storage(会话存储)

// Session Storage 在浏览器会话期间有效,关闭标签页后清除
sessionStorage.setItem('sessionId', 'abc123');
const sessionId = sessionStorage.getItem('sessionId');

// 与 Local Storage 用法相同,但生命周期不同

6.3 存储事件监听

// 监听存储变化(在其他标签页修改时触发)
window.addEventListener('storage', (event) => {
    console.log('存储变化:', {
        key: event.key,
        oldValue: event.oldValue,
        newValue: event.newValue,
        url: event.url
    });
});

7. 拖放 API(Drag and Drop)

<div id="dragSource" draggable="true" style="width:100px; height:100px; background:lightblue; margin:10px;">
    拖我
</div>

<div id="dropZone" style="width:200px; height:100px; background:lightgray; margin:10px; border:2px dashed #999;">
    放置区域
</div>

<script>
const dragSource = document.getElementById('dragSource');
const dropZone = document.getElementById('dropZone');

// 拖拽开始
dragSource.addEventListener('dragstart', (e) => {
    e.dataTransfer.setData('text/plain', '拖拽的数据');
    e.dataTransfer.effectAllowed = 'move';
    dragSource.style.opacity = '0.5';
});

// 拖拽结束
dragSource.addEventListener('dragend', () => {
    dragSource.style.opacity = '1';
});

// 允许放置
dropZone.addEventListener('dragover', (e) => {
    e.preventDefault(); // 必须阻止默认行为
    e.dataTransfer.dropEffect = 'move';
    dropZone.style.backgroundColor = 'lightgreen';
});

// 离开放置区域
dropZone.addEventListener('dragleave', () => {
    dropZone.style.backgroundColor = 'lightgray';
});

// 放置操作
dropZone.addEventListener('drop', (e) => {
    e.preventDefault();
    const data = e.dataTransfer.getData('text/plain');
    dropZone.textContent = `放置的数据:${data}`;
    dropZone.style.backgroundColor = 'lightgreen';
});
</script>

8. 地理定位(Geolocation API)

// 检查浏览器是否支持
if ('geolocation' in navigator) {
    // 获取当前位置
    navigator.geolocation.getCurrentPosition(
        (position) => {
            console.log('纬度:', position.coords.latitude);
            console.log('经度:', position.coords.longitude);
            console.log('精度:', position.coords.accuracy);
            
            // 显示在地图上(示例)
            const lat = position.coords.latitude;
            const lng = position.coords.longitude;
            const mapUrl = `https://www.google.com/maps?q=${lat},${lng}`;
            window.open(mapUrl, '_blank');
        },
        (error) => {
            console.error('获取位置失败:', error.message);
            switch(error.code) {
                case error.PERMISSION_DENIED:
                    console.log('用户拒绝获取位置');
                    break;
                case error.POSITION_UNAVAILABLE:
                    console.log('位置信息不可用');
                    break;
                case error.TIMEOUT:
                    console.log('请求超时');
                    break;
            }
        },
        {
            enableHighAccuracy: true,
            timeout: 5000,
            maximumAge: 0
        }
    );
    
    // 持续监听位置变化
    const watchId = navigator.geolocation.watchPosition(
        (position) => {
            console.log('位置更新:', position.coords.latitude, position.coords.longitude);
        },
        (error) => {
            console.error('位置更新错误:', error.message);
        }
    );
    
    // 停止监听
    // navigator.geolocation.clearWatch(watchId);
} else {
    console.log('浏览器不支持地理定位');
}

9. Web Workers(后台线程)

<button id="startWorker">启动 Worker</button>
<button id="stopWorker">停止 Worker</button>
<div id="result"></div>

<script>
let worker;

document.getElementById('startWorker').addEventListener('click', () => {
    if (typeof(Worker) !== 'undefined') {
        worker = new Worker('worker.js');
        
        worker.onmessage = (e) => {
            document.getElementById('result').textContent = `计算结果:${e.data}`;
        };
        
        worker.postMessage('开始计算');
    } else {
        console.log('浏览器不支持 Web Workers');
    }
});

document.getElementById('stopWorker').addEventListener('click', () => {
    if (worker) {
        worker.terminate();
        document.getElementById('result').textContent = 'Worker 已停止';
    }
});
</script>

worker.js 文件内容:

self.onmessage = (e) => {
    if (e.data === '开始计算') {
        let sum = 0;
        for (let i = 0; i < 1000000000; i++) {
            sum += i;
        }
        self.postMessage(sum);
    }
};

10. 响应式设计基础

10.1 视口设置

<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">

10.2 媒体查询示例

<style>
/* 默认样式(移动端优先) */
.container {
    width: 100%;
    padding: 10px;
}

/* 平板设备 */
@media (min-width: 768px) {
    .container {
        width: 750px;
        margin: 0 auto;
    }
}

/* 桌面设备 */
@media (min-width: 992px) {
    .container {
        width: 970px;
    }
}

/* 大屏幕 */
@media (min-width: 1200px) {
    .container {
        width: 1170px;
    }
}

/* 横屏模式 */
@media (orientation: landscape) {
    .sidebar {
        display: block;
    }
}

/* 打印样式 */
@media print {
    .no-print {
        display: none;
    }
}
</style>

11. 新特性总结表

特性 说明 浏览器支持
语义化标签 <header>, <nav>, <article> 所有现代浏览器
表单增强 新输入类型、验证属性 所有现代浏览器
多媒体 <audio>, <video> 所有现代浏览器
Canvas 2D/3D图形绘制 所有现代浏览器
SVG 矢量图形 所有现代浏览器
本地存储 localStorage, sessionStorage 所有现代浏览器
拖放API 原生拖放功能 所有现代浏览器
地理定位 获取用户位置 所有现代浏览器
Web Workers 后台线程 所有现代浏览器
离线应用 Application Cache(已废弃,推荐 Service Workers) 部分支持
Service Workers 离线缓存、推送通知 现代浏览器

12. 最佳实践

12.1 代码规范

<!-- 推荐 -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>页面标题</title>
</head>
<body>
    <header>
        <nav>
            <ul>
                <li><a href="#home">首页</a></li>
            </ul>
        </nav>
    </header>
    <main>
        <article>
            <h1>文章标题</h1>
            <p>文章内容...</p>
        </article>
    </main>
    <footer>
        <p>版权信息</p>
    </footer>
</body>
</html>

12.2 性能优化

  1. 压缩资源:压缩 CSS、JS、图片
  2. 懒加载:图片、视频延迟加载
  3. CDN:使用内容分发网络
  4. 缓存策略:合理使用本地存储和浏览器缓存
  5. 减少HTTP请求:合并文件、使用雪碧图

12.3 可访问性(Accessibility)

<!-- 为图片添加alt属性 -->
<img src="logo.png" alt="公司Logo">

<!-- 为表单添加label -->
<label for="username">用户名:</label>
<input type="text" id="username" name="username">

<!-- 使用ARIA属性 -->
<div role="navigation" aria-label="主导航">
    <ul>
        <li><a href="#home">首页</a></li>
    </ul>
</div>

<!-- 键盘导航 -->
<button tabindex="0">可聚焦按钮</button>

13. 实战项目示例

13.1 响应式博客页面

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>我的博客</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        
        body {
            font-family: Arial, sans-serif;
            line-height: 1.6;
            color: #333;
        }
        
        .container {
            max-width: 1200px;
            margin: 0 auto;
            padding: 0 20px;
        }
        
        header {
            background: #333;
            color: white;
            padding: 1rem 0;
        }
        
        nav ul {
            list-style: none;
            display: flex;
            gap: 20px;
        }
        
        nav a {
            color: white;
            text-decoration: none;
        }
        
        main {
            padding: 2rem 0;
        }
        
        article {
            margin-bottom: 2rem;
            padding: 1.5rem;
            background: #f9f9f9;
            border-radius: 5px;
        }
        
        footer {
            background: #333;
            color: white;
            text-align: center;
            padding: 1rem 0;
            margin-top: 2rem;
        }
        
        @media (max-width: 768px) {
            nav ul {
                flex-direction: column;
                gap: 10px;
            }
        }
    </style>
</head>
<body>
    <header>
        <div class="container">
            <h1>我的博客</h1>
            <nav>
                <ul>
                    <li><a href="#home">首页</a></li>
                    <li><a href="#about">关于</a></li>
                    <li><a href="#contact">联系</a></li>
                </ul>
            </nav>
        </div>
    </header>
    
    <main class="container">
        <article>
            <h2>HTML5 新特性</h2>
            <time datetime="2024-01-15">2024年1月15日</time>
            <p>HTML5 引入了许多新特性,包括语义化标签、多媒体支持等...</p>
            <a href="#">阅读全文</a>
        </article>
        
        <article>
            <h2>CSS3 动画效果</h2>
            <time datetime="2024-01-10">2024年1月10日</time>
            <p>CSS3 提供了强大的动画和过渡效果...</p>
            <a href="#">阅读全文</a>
        </article>
    </main>
    
    <footer>
        <div class="container">
            <p>&copy; 2024 我的博客. 保留所有权利。</p>
        </div>
    </footer>
</body>
</html>

学习建议

  1. 循序渐进:从基础标签开始,逐步学习高级特性
  2. 动手实践:每个示例都要亲自编写和运行
  3. 跨浏览器测试:确保代码在不同浏览器中正常工作
  4. 响应式设计:始终考虑移动设备兼容性
  5. 可访问性:确保所有用户都能访问你的网站
  6. 性能优化:关注页面加载速度和用户体验
  7. 持续学习:关注 Web 技术的新发展

这份学习笔记涵盖了 HTML5 的核心知识点,建议结合实际项目进行练习,逐步掌握现代 Web 开发技术。

Logo

有“AI”的1024 = 2048,欢迎大家加入2048 AI社区

更多推荐