HTML相关

14 minute read

HTML 前端开发 完整系统学习大纲


一、HTML 基础与历史

1.1 HTML 发展历史

  • HTML 1.0 (1991):Tim Berners-Lee 创建,18个标签
  • HTML 2.0 (1995):成为IETF标准
  • HTML 3.2 (1997):W3C标准,表格、applet、文本流
  • HTML 4.01 (1999):CSS支持,框架,国际化
  • XHTML 1.0 (2000):XML语法,更严格
  • HTML5 (2014):现代Web标准,语义化,多媒体
  • HTML5.1/5.2/5.3:持续演进,新增API

1.2 HTML 核心概念

  • 超文本标记语言:HyperText Markup Language
  • 标记语言 vs 编程语言
  • 浏览器渲染流程:解析 → 构建DOM → 渲染
  • Web标准三剑客:HTML(结构)、CSS(表现)、JavaScript(行为)

1.3 第一个HTML页面

<!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>
    <h1>你好,世界!</h1>
    <p>这是我的第一个HTML页面。</p>
</body>
</html>

1.4 开发工具与环境

  1. 编辑器:VS Code、Sublime Text、WebStorm
  2. 浏览器:Chrome、Firefox、Safari、Edge
  3. 开发者工具:元素检查、控制台、网络分析
  4. 本地服务器:Live Server、http-server

二、HTML 基础语法

2.1 HTML 文档结构

<!-- 文档类型声明 -->
<!DOCTYPE html>

<!-- 根元素 -->
<html lang="zh-CN">

<!-- 头部:元数据和资源引用 -->
<head>
    <!-- 字符编码 -->
    <meta charset="UTF-8">
    
    <!-- 视口设置,响应式必备 -->
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    
    <!-- 页面标题 -->
    <title>页面标题</title>
    
    <!-- 引入CSS -->
    <link rel="stylesheet" href="styles.css">
    
    <!-- 引入图标 -->
    <link rel="icon" href="favicon.ico" type="image/x-icon">
    
    <!-- 引入JavaScript -->
    <script src="script.js" defer></script>
</head>

<!-- 主体:页面内容 -->
<body>
    <!-- 页面内容在这里 -->
</body>
</html>

2.2 元素与标签

  • 开始标签<tagname>
  • 结束标签</tagname>
  • 空元素<br><br/>
  • 属性<tagname attribute="value">
  • 嵌套规则:正确嵌套,不能交叉
<!-- 正确嵌套 -->
<div>
    <p>这是<span>嵌套</span>示例</p>
</div>

<!-- 错误嵌套(交叉) -->
<div>
    <p>错误<span>嵌套</div></span></p>

2.3 属性类型

  1. 全局属性:所有元素都可用
    • id:唯一标识
    • class:类名
    • style:内联样式
    • title:工具提示
    • data-*:自定义数据
    <div id="header" class="main-header" title="网站标题" data-role="navigation">
        内容
    </div>
    
  2. 事件属性:响应用户交互
    • onclickonmouseoveronload
    <button onclick="alert('点击了按钮')">点击我</button>
    
  3. 特定属性:特定元素的属性
    • srchrefalttype

2.4 注释与实体

<!-- 这是HTML注释,不会在浏览器中显示 -->

<!-- 
    多行
    注释
-->

<!-- 特殊字符实体 -->
&lt;    <!-- 小于号 < -->
&gt;    <!-- 大于号 > -->
&amp;   <!-- 和号 & -->
&quot;  <!-- 双引号 " -->
&apos;  <!-- 单引号 ' -->
&nbsp;  <!-- 不换行空格 -->
&copy;  <!-- 版权符号 © -->
&reg;   <!-- 注册商标 ® -->
&trade; <!-- 商标符号 ™ -->
&euro;  <!-- 欧元符号 € -->
&pound; <!-- 英镑符号 £ -->
&yen;   <!-- 日元符号 ¥ -->

三、文本与格式化

3.1 标题元素

<h1>一级标题</h1>  <!-- 最重要的标题,页面通常只有一个h1 -->
<h2>二级标题</h2>
<h3>三级标题</h3>
<h4>四级标题</h4>
<h5>五级标题</h5>
<h6>六级标题</h6>

3.2 段落与换行

<!-- 段落 -->
<p>这是一个段落。HTML会将连续的空白符合并为一个空格。</p>
<p>这是另一个段落。段落之间会有默认的间距。</p>

<!-- 换行 -->
<p>第一行<br>第二行<br>第三行</p>

<!-- 水平线 -->
<hr>

<!-- 预格式化文本,保留空格和换行 -->
<pre>
    这
        是
            预
                格式化
                    文本
</pre>

3.3 文本格式化

<!-- 物理样式 -->
<b>粗体文本</b>
<i>斜体文本</i>
<u>下划线文本</u>
<s>删除线文本</s>
<mark>高亮文本</mark>
<sub>下标文本</sub>
<sup>上标文本</sup>

<!-- 逻辑样式 -->
<strong>重要文本(语义化粗体)</strong>
<em>强调文本(语义化斜体)</em>
<small>小号文本</small>
<code>代码片段</code>
<kbd>键盘输入</kbd>
<samp>程序输出</samp>
<var>变量</var>

<!-- 引用 -->
<blockquote cite="来源URL">
    这是引用文本,通常会有缩进。
</blockquote>
<q>短引用</q>
<cite>引用来源</cite>

<!-- 缩写 -->
<abbr title="HyperText Markup Language">HTML</abbr>

<!-- 地址 -->
<address>
    联系人:张三<br>
    地址:北京市朝阳区<br>
    电话:138-0000-0000
</address>

3.4 列表

  1. 无序列表

    <ul>
        <li>列表项1</li>
        <li>列表项2
            <ul>
                <li>嵌套列表项1</li>
                <li>嵌套列表项2</li>
            </ul>
        </li>
        <li>列表项3</li>
    </ul>
    
  2. 有序列表

    <ol>
        <li>第一步</li>
        <li>第二步
            <ol type="a">
                <li>子步骤a</li>
                <li>子步骤b</li>
            </ol>
        </li>
        <li>第三步</li>
    </ol>
    
    <!-- 列表属性 -->
    <ol type="1" start="10" reversed>
        <li>项目10</li>
        <li>项目9</li>
        <li>项目8</li>
    </ol>
    
  3. 定义列表

    <dl>
        <dt>HTML</dt>
        <dd>超文本标记语言,用于创建网页结构</dd>
            
        <dt>CSS</dt>
        <dd>层叠样式表,用于控制网页表现</dd>
            
        <dt>JavaScript</dt>
        <dd>脚本语言,用于实现网页交互</dd>
    </dl>
    

3.5 链接

<!-- 基本链接 -->
<a href="https://www.example.com">访问示例网站</a>

<!-- 相对路径 -->
<a href="about.html">关于我们</a>
<a href="products/index.html">产品列表</a>
<a href="../contact.html">联系我们</a>

<!-- 锚点链接 -->
<a href="#section1">跳转到第一节</a>
<h2 id="section1">第一节</h2>

<!-- 下载链接 -->
<a href="document.pdf" download>下载PDF文档</a>

<!-- 邮件链接 -->
<a href="mailto:contact@example.com?subject=咨询&body=您好,我想咨询...">发送邮件</a>

<!-- 电话链接 -->
<a href="tel:+8613800000000">拨打电话</a>

<!-- 目标窗口 -->
<a href="https://www.example.com" target="_blank" rel="noopener noreferrer">新窗口打开</a>

<!-- 链接关系 -->
<a href="styles.css" rel="stylesheet">样式表</a>
<a href="next.html" rel="next">下一页</a>
<a href="prev.html" rel="prev">上一页</a>

四、图像与多媒体

4.1 图像

<!-- 基本图片 -->
<img src="image.jpg" alt="图片描述">

<!-- 响应式图片 -->
<img src="image.jpg" alt="描述" width="800" height="600">

<!-- 图片属性 -->
<img src="image.jpg" 
     alt="详细的图片描述文本"
     width="400"
     height="300"
     loading="lazy"           <!-- 延迟加载 -->
     decoding="async"         <!-- 异步解码 -->
     srcset="image-320w.jpg 320w,
             image-480w.jpg 480w,
             image-800w.jpg 800w"
     sizes="(max-width: 600px) 480px,
            800px">

<!-- 图片地图 -->
<img src="planets.jpg" alt="行星" usemap="#planetmap">
<map name="planetmap">
    <area shape="rect" coords="0,0,82,126" href="sun.html" alt="太阳">
    <area shape="circle" coords="90,58,3" href="mercury.html" alt="水星">
    <area shape="circle" coords="124,58,8" href="venus.html" alt="金星">
</map>

<!-- 图片格式 -->
<img src="photo.webp" alt="WebP格式">  <!-- 现代格式,压缩率高 -->
<img src="photo.avif" alt="AVIF格式">  <!-- 最新格式,性能更好 -->

4.2 音频

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

<!-- 完整音频控件 -->
<audio controls
       autoplay
       loop
       muted
       preload="metadata"
       src="sound.mp3">
</audio>

<!-- 自定义音频播放器 -->
<audio id="myAudio">
    <source src="music.mp3" type="audio/mpeg">
</audio>
<div>
    <button onclick="document.getElementById('myAudio').play()">播放</button>
    <button onclick="document.getElementById('myAudio').pause()">暂停</button>
    <button onclick="document.getElementById('myAudio').volume += 0.1">增加音量</button>
    <button onclick="document.getElementById('myAudio').volume -= 0.1">降低音量</button>
</div>

4.3 视频

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

<!-- 完整视频控件 -->
<video controls
       autoplay
       loop
       muted
       preload="metadata"
       poster="poster.jpg"
       width="800"
       height="450">
    <source src="movie.mp4" type="video/mp4">
    <track src="subtitles_en.vtt" kind="subtitles" srclang="en" label="English">
    <track src="subtitles_zh.vtt" kind="subtitles" srclang="zh" label="中文" default>
</video>

<!-- 响应式视频 -->
<div style="position: relative; padding-bottom: 56.25%; height: 0;">
    <video style="position: absolute; top: 0; left: 0; width: 100%; height: 100%;"
           controls
           src="video.mp4">
    </video>
</div>

4.4 画布与SVG

  1. Canvas

    <canvas id="myCanvas" width="400" height="200" style="border:1px solid #000;">
        您的浏览器不支持Canvas。
    </canvas>
    <script>
        const canvas = document.getElementById('myCanvas');
        const ctx = canvas.getContext('2d');
        ctx.fillStyle = 'green';
        ctx.fillRect(10, 10, 150, 100);
    </script>
    
  2. SVG

    <svg width="200" height="200">
        <circle cx="100" cy="100" r="80" fill="red" />
        <rect x="50" y="50" width="100" height="60" fill="blue" opacity="0.5" />
        <text x="100" y="100" text-anchor="middle" fill="white">SVG</text>
    </svg>
    

4.5 嵌入内容

<!-- 嵌入网页 -->
<iframe src="https://www.example.com" 
        width="800" 
        height="600"
        title="示例网站"
        loading="lazy"
        sandbox="allow-same-origin allow-scripts"
        allow="camera; microphone">
</iframe>

<!-- 嵌入PDF -->
<embed src="document.pdf" type="application/pdf" width="100%" height="600px">

<!-- 嵌入对象 -->
<object data="movie.swf" type="application/x-shockwave-flash" width="400" height="300">
    <param name="movie" value="movie.swf">
</object>

<!-- 嵌入Flash(已废弃,仅作历史了解) -->
<!-- 现代Web已不再使用Flash -->

五、表格

5.1 基础表格

<table border="1">
    <caption>学生成绩表</caption>
    <tr>
        <th>学号</th>
        <th>姓名</th>
        <th>语文</th>
        <th>数学</th>
        <th>英语</th>
    </tr>
    <tr>
        <td>001</td>
        <td>张三</td>
        <td>90</td>
        <td>85</td>
        <td>92</td>
    </tr>
    <tr>
        <td>002</td>
        <td>李四</td>
        <td>88</td>
        <td>92</td>
        <td>87</td>
    </tr>
</table>

5.2 完整表格结构

<table>
    <caption>2024年销售数据</caption>
    
    <thead>
        <tr>
            <th scope="col">季度</th>
            <th scope="col">产品A</th>
            <th scope="col">产品B</th>
            <th scope="col">产品C</th>
            <th scope="col">总计</th>
        </tr>
    </thead>
    
    <tbody>
        <tr>
            <th scope="row">第一季度</th>
            <td>¥120,000</td>
            <td>¥80,000</td>
            <td>¥60,000</td>
            <td>¥260,000</td>
        </tr>
        <tr>
            <th scope="row">第二季度</th>
            <td>¥150,000</td>
            <td>¥90,000</td>
            <td>¥70,000</td>
            <td>¥310,000</td>
        </tr>
    </tbody>
    
    <tfoot>
        <tr>
            <th scope="row">总计</th>
            <td>¥270,000</td>
            <td>¥170,000</td>
            <td>¥130,000</td>
            <td>¥570,000</td>
        </tr>
    </tfoot>
</table>

5.3 复杂表格

<table>
    <colgroup>
        <col span="2" style="background-color: #f0f0f0;">
        <col style="background-color: #e0e0e0;">
    </colgroup>
    
    <thead>
        <tr>
            <th colspan="2">基本信息</th>
            <th rowspan="2">成绩</th>
        </tr>
        <tr>
            <th>姓名</th>
            <th>班级</th>
        </tr>
    </thead>
    
    <tbody>
        <tr>
            <td>张三</td>
            <td>三年一班</td>
            <td>95</td>
        </tr>
        <tr>
            <td>李四</td>
            <td>三年二班</td>
            <td>88</td>
        </tr>
    </tbody>
</table>

5.4 表格高级特性

<!-- 可排序表格 -->
<table id="sortable">
    <thead>
        <tr>
            <th onclick="sortTable(0)">姓名</th>
            <th onclick="sortTable(1)">年龄</th>
            <th onclick="sortTable(2)">分数</th>
        </tr>
    </thead>
    <tbody>
        <tr><td>张三</td><td>20</td><td>85</td></tr>
        <tr><td>李四</td><td>22</td><td>92</td></tr>
    </tbody>
</table>

<!-- 响应式表格 -->
<div style="overflow-x: auto;">
    <table style="min-width: 600px;">
        <!-- 宽表格内容 -->
    </table>
</div>

六、表单

6.1 基本表单

<form action="/submit" method="POST" enctype="application/x-www-form-urlencoded">
    <!-- 表单控件 -->
    <label for="username">用户名:</label>
    <input type="text" id="username" name="username" required>
    
    <label for="password">密码:</label>
    <input type="password" id="password" name="password" minlength="6" required>
    
    <button type="submit">提交</button>
    <button type="reset">重置</button>
</form>

6.2 输入类型

<!-- 文本输入 -->
<input type="text" placeholder="请输入文本">
<input type="search" placeholder="搜索...">
<input type="email" placeholder="邮箱" multiple>
<input type="url" placeholder="网址">
<input type="tel" placeholder="电话">
<input type="password" placeholder="密码">

<!-- 数字输入 -->
<input type="number" min="0" max="100" step="1" value="50">
<input type="range" min="0" max="100" value="50">

<!-- 日期时间 -->
<input type="date">
<input type="time">
<input type="datetime-local">
<input type="month">
<input type="week">

<!-- 选择 -->
<input type="color" value="#ff0000">
<input type="file" accept=".jpg,.png,.pdf" multiple>

<!-- 按钮 -->
<input type="submit" value="提交">
<input type="reset" value="重置">
<input type="button" value="普通按钮">
<input type="image" src="button.png" alt="图片按钮">

<!-- 隐藏字段 -->
<input type="hidden" name="token" value="abc123">

6.3 选择控件

<!-- 单选按钮 -->
<fieldset>
    <legend>性别</legend>
    <label>
        <input type="radio" name="gender" value="male" checked></label>
    <label>
        <input type="radio" name="gender" value="female"></label>
    <label>
        <input type="radio" name="gender" value="other"> 其他
    </label>
</fieldset>

<!-- 复选框 -->
<fieldset>
    <legend>兴趣爱好</legend>
    <label>
        <input type="checkbox" name="hobby" value="reading"> 阅读
    </label>
    <label>
        <input type="checkbox" name="hobby" value="music"> 音乐
    </label>
    <label>
        <input type="checkbox" name="hobby" value="sports"> 运动
    </label>
</fieldset>

<!-- 下拉选择 -->
<label for="country">国家:</label>
<select id="country" name="country">
    <option value="">请选择</option>
    <option value="cn" selected>中国</option>
    <option value="us">美国</option>
    <option value="jp">日本</option>
    <optgroup label="欧洲">
        <option value="uk">英国</option>
        <option value="fr">法国</option>
    </optgroup>
</select>

<!-- 多选列表 -->
<label for="skills">技能:</label>
<select id="skills" name="skills" multiple size="4">
    <option value="html">HTML</option>
    <option value="css">CSS</option>
    <option value="js">JavaScript</option>
    <option value="react">React</option>
</select>

6.4 文本区域

<label for="message">留言:</label>
<textarea id="message" 
          name="message" 
          rows="5" 
          cols="50"
          placeholder="请输入您的留言..."
          minlength="10"
          maxlength="500"
          wrap="hard"
          spellcheck="true">
    默认文本内容
</textarea>

6.5 表单高级特性

<form id="myForm" novalidate>
    <!-- 数据列表 -->
    <label for="browser">浏览器:</label>
    <input list="browsers" id="browser" name="browser">
    <datalist id="browsers">
        <option value="Chrome">
        <option value="Firefox">
        <option value="Safari">
        <option value="Edge">
    </datalist>
    
    <!-- 输出元素 -->
    <label for="range">音量:</label>
    <input type="range" id="range" name="range" value="50" oninput="output.value = this.value">
    <output id="output" for="range">50</output>
    
    <!-- 进度条 -->
    <label for="progress">进度:</label>
    <progress id="progress" value="75" max="100">75%</progress>
    
    <!-- 仪表 -->
    <label for="meter">使用量:</label>
    <meter id="meter" value="0.6" min="0" max="1" low="0.2" high="0.8" optimum="0.5">60%</meter>
    
    <!-- 验证模式 -->
    <label for="pattern">4位数字:</label>
    <input type="text" id="pattern" pattern="\d{4}" title="请输入4位数字">
    
    <!-- 自动完成 -->
    <label for="name">姓名:</label>
    <input type="text" id="name" name="name" autocomplete="name">
    
    <!-- 步骤控制 -->
    <label for="step">步骤:</label>
    <input type="number" id="step" step="0.5" min="0" max="10">
</form>

6.6 表单验证

<form id="validatedForm">
    <!-- 必填验证 -->
    <label for="username">用户名(必填):</label>
    <input type="text" id="username" name="username" required>
    
    <!-- 长度验证 -->
    <label for="password">密码(6-20位):</label>
    <input type="password" id="password" name="password" 
           minlength="6" maxlength="20" required>
    
    <!-- 格式验证 -->
    <label for="email">邮箱:</label>
    <input type="email" id="email" name="email" required>
    
    <!-- 范围验证 -->
    <label for="age">年龄(18-100):</label>
    <input type="number" id="age" name="age" min="18" max="100" required>
    
    <!-- 自定义验证 -->
    <label for="phone">手机号:</label>
    <input type="tel" id="phone" name="phone" 
           pattern="1[3-9]\d{9}" 
           title="请输入正确的手机号码"
           required>
    
    <!-- 自定义验证消息 -->
    <label for="custom">自定义验证:</label>
    <input type="text" id="custom" name="custom" 
           oninvalid="this.setCustomValidity('请填写此字段')"
           oninput="this.setCustomValidity('')">
    
    <button type="submit">提交</button>
</form>

七、语义化元素

7.1 文档结构语义

<!-- 页面容器 -->
<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>

<!-- 主导航 -->
<nav aria-label="主导航">
    <!-- 导航内容 -->
</nav>

<!-- 主要内容 -->
<main>
    <!-- 文章内容 -->
    <article>
        <header>
            <h2>文章标题</h2>
            <p>发布时间:<time datetime="2024-01-15">2024年1月15日</time></p>
        </header>
        
        <section>
            <h3>第一节</h3>
            <p>文章内容...</p>
        </section>
        
        <aside>
            <h4>相关链接</h4>
            <ul>
                <li><a href="#related">相关文章</a></li>
            </ul>
        </aside>
    </article>
    
    <!-- 独立内容 -->
    <section>
        <h2>产品介绍</h2>
        <p>产品描述...</p>
    </section>
</main>

<!-- 侧边栏 -->
<aside>
    <h3>侧边栏</h3>
    <p>广告、链接等内容...</p>
</aside>

<!-- 页脚 -->
<footer>
    <p>&copy; 2024 我的网站</p>
    <address>
        联系地址:北京市朝阳区
    </address>
</footer>

7.2 文本语义

<!-- 强调 -->
<p><em>请注意</em>,这个功能非常重要。</p>

<!-- 重要 -->
<p><strong>警告!</strong> 不要删除此文件。</p>

<!-- 标记 -->
<p>搜索关键词:<mark>HTML5</mark></p>

<!-- 时间 -->
<p>会议时间:<time datetime="2024-12-25T20:00">圣诞节晚上8点</time></p>

<!-- 代码 -->
<p>使用<code>console.log()</code>输出信息。</p>

<!-- 键盘输入 -->
<p><kbd>Ctrl</kbd>+<kbd>C</kbd>复制。</p>

<!-- 变量 -->
<p><var>x</var> = 10。</p>

<!-- 输出 -->
<p>结果:<samp>操作成功</samp></p>

7.3 交互语义

<!-- 详情/摘要 -->
<details>
    <summary>点击查看详情</summary>
    <p>这里是详细内容...</p>
</details>

<!-- 对话框 -->
<dialog id="myDialog">
    <p>这是一个对话框</p>
    <button onclick="document.getElementById('myDialog').close()">关闭</button>
</dialog>
<button onclick="document.getElementById('myDialog').showModal()">打开对话框</button>

<!-- 菜单 -->
<menu>
    <li><button>新建</button></li>
    <li><button>打开</button></li>
    <li><button>保存</button></li>
</menu>

八、元信息

8.1 文档元信息

<!-- 字符编码 -->
<meta charset="UTF-8">

<!-- 视口设置 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=5.0, user-scalable=yes">

<!-- IE兼容模式 -->
<meta http-equiv="X-UA-Compatible" content="IE=edge">

<!-- 页面描述 -->
<meta name="description" content="网站描述,用于搜索引擎显示">

<!-- 关键词 -->
<meta name="keywords" content="HTML, CSS, JavaScript, 前端开发">

<!-- 作者 -->
<meta name="author" content="张三">

<!-- 版权 -->
<meta name="copyright" content="© 2024 My Company">

<!-- 生成工具 -->
<meta name="generator" content="Visual Studio Code">

8.2 社交分享

<!-- Open Graph (Facebook, LinkedIn) -->
<meta property="og:title" content="页面标题">
<meta property="og:description" content="页面描述">
<meta property="og:image" content="https://example.com/image.jpg">
<meta property="og:url" content="https://example.com/page.html">
<meta property="og:type" content="website">
<meta property="og:site_name" content="网站名称">
<meta property="og:locale" content="zh_CN">

<!-- Twitter Cards -->
<meta name="twitter:card" content="summary_large_image">
<meta name="twitter:title" content="页面标题">
<meta name="twitter:description" content="页面描述">
<meta name="twitter:image" content="https://example.com/image.jpg">
<meta name="twitter:site" content="@username">
<meta name="twitter:creator" content="@author">

<!-- 其他社交 -->
<meta property="fb:app_id" content="你的Facebook App ID">
<meta name="pinterest" content="nopin"> <!-- 禁止Pinterest保存 -->

8.3 SEO优化

<!-- 搜索引擎 -->
<meta name="robots" content="index, follow">
<meta name="googlebot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">
<meta name="bingbot" content="index, follow, max-snippet:-1, max-image-preview:large, max-video-preview:-1">

<!-- 规范化URL -->
<link rel="canonical" href="https://example.com/page">

<!-- 多语言 -->
<link rel="alternate" hreflang="en" href="https://example.com/en/">
<link rel="alternate" hreflang="zh" href="https://example.com/zh/">
<link rel="alternate" hreflang="x-default" href="https://example.com/">

<!-- 站点地图 -->
<link rel="sitemap" type="application/xml" href="/sitemap.xml">

<!-- 结构化数据 -->
<script type="application/ld+json">
{
  "@context": "https://schema.org",
  "@type": "WebSite",
  "name": "我的网站",
  "url": "https://example.com"
}
</script>

8.4 移动端优化

<!-- 主题颜色 -->
<meta name="theme-color" content="#ffffff">
<meta name="msapplication-TileColor" content="#ffffff">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

<!-- 移动端优化 -->
<meta name="HandheldFriendly" content="True">
<meta name="MobileOptimized" content="320">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-title" content="应用名称">

<!-- 启动画面 -->
<link rel="apple-touch-startup-image" href="splash.png">

<!-- 图标 -->
<link rel="apple-touch-icon" sizes="180x180" href="/apple-touch-icon.png">
<link rel="icon" type="image/png" sizes="32x32" href="/favicon-32x32.png">
<link rel="icon" type="image/png" sizes="16x16" href="/favicon-16x16.png">
<link rel="manifest" href="/site.webmanifest">
<link rel="mask-icon" href="/safari-pinned-tab.svg" color="#5bbad5">
<meta name="msapplication-TileImage" content="/mstile-144x144.png">

8.5 性能优化

<!-- 预加载 -->
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<link rel="preload" href="image.jpg" as="image">
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="critical.js" as="script">

<!-- 预连接 -->
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>

<!-- 预获取 -->
<link rel="prefetch" href="next-page.html">
<link rel="dns-prefetch" href="//cdn.example.com">

<!-- 预渲染 -->
<link rel="prerender" href="https://example.com/next-page">

<!-- 资源提示 -->
<link rel="stylesheet" href="styles.css" media="print" onload="this.media='all'">

九、HTML5 API

9.1 Canvas API

<canvas id="myCanvas" width="800" height="600"></canvas>
<script>
const canvas = document.getElementById('myCanvas');
const ctx = canvas.getContext('2d');

// 绘制矩形
ctx.fillStyle = 'red';
ctx.fillRect(10, 10, 150, 100);

// 绘制文本
ctx.font = '30px Arial';
ctx.fillStyle = 'blue';
ctx.fillText('Hello Canvas', 10, 150);

// 绘制路径
ctx.beginPath();
ctx.moveTo(75, 50);
ctx.lineTo(100, 75);
ctx.lineTo(100, 25);
ctx.fill();

// 绘制圆形
ctx.beginPath();
ctx.arc(200, 200, 50, 0, Math.PI * 2);
ctx.fillStyle = 'green';
ctx.fill();

// 渐变
const gradient = ctx.createLinearGradient(0, 0, 200, 0);
gradient.addColorStop(0, 'red');
gradient.addColorStop(1, 'blue');
ctx.fillStyle = gradient;
ctx.fillRect(300, 10, 150, 100);

// 图片绘制
const img = new Image();
img.onload = function() {
    ctx.drawImage(img, 10, 300, 100, 100);
};
img.src = 'image.jpg';
</script>

9.2 Geolocation API

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

<script>
function getLocation() {
    if (navigator.geolocation) {
        navigator.geolocation.getCurrentPosition(
            showPosition,
            showError,
            {
                enableHighAccuracy: true,
                timeout: 5000,
                maximumAge: 0
            }
        );
    } else {
        document.getElementById("location").innerHTML = "浏览器不支持地理位置";
    }
}

function showPosition(position) {
    const lat = position.coords.latitude;
    const lon = position.coords.longitude;
    const accuracy = position.coords.accuracy;
    
    document.getElementById("location").innerHTML = 
        `纬度: ${lat}<br>经度: ${lon}<br>精度: ${accuracy}米`;
        
    // 更新位置
    const watchId = navigator.geolocation.watchPosition(updatePosition);
}

function updatePosition(position) {
    console.log("位置更新:", position.coords);
}

function showError(error) {
    switch(error.code) {
        case error.PERMISSION_DENIED:
            alert("用户拒绝地理位置请求");
            break;
        case error.POSITION_UNAVAILABLE:
            alert("位置信息不可用");
            break;
        case error.TIMEOUT:
            alert("请求超时");
            break;
        case error.UNKNOWN_ERROR:
            alert("未知错误");
            break;
    }
}
</script>

9.3 Web Storage

<script>
// localStorage - 永久存储
localStorage.setItem('username', '张三');
localStorage.setItem('theme', 'dark');

const username = localStorage.getItem('username');
const theme = localStorage.getItem('theme');

// 存储对象
const user = { name: '李四', age: 25 };
localStorage.setItem('user', JSON.stringify(user));
const storedUser = JSON.parse(localStorage.getItem('user'));

// 删除
localStorage.removeItem('username');
localStorage.clear();

// sessionStorage - 会话存储
sessionStorage.setItem('sessionData', '临时数据');

// 存储事件
window.addEventListener('storage', function(event) {
    console.log('Storage changed:', event.key, event.newValue);
});

// 存储使用量
function getStorageUsage() {
    let total = 0;
    for (let key in localStorage) {
        if (localStorage.hasOwnProperty(key)) {
            total += localStorage[key].length * 2; // UTF-16
        }
    }
    console.log('已使用:', total / 1024, 'KB');
    console.log('总空间:', 5 * 1024, 'KB (通常5MB)');
}
</script>

9.4 Service Workers

<script>
// 注册Service Worker
if ('serviceWorker' in navigator) {
    window.addEventListener('load', function() {
        navigator.serviceWorker.register('/sw.js')
            .then(function(registration) {
                console.log('ServiceWorker注册成功:', registration.scope);
            })
            .catch(function(error) {
                console.log('ServiceWorker注册失败:', error);
            });
    });
}

// 检查更新
navigator.serviceWorker.ready.then(function(registration) {
    registration.update();
});

// 通信
navigator.serviceWorker.addEventListener('message', function(event) {
    console.log('收到消息:', event.data);
});

// 发送消息
navigator.serviceWorker.controller.postMessage('Hello');
</script>

9.5 其他HTML5 API

  1. Web Workers

    <script>
    // 主线程
    const worker = new Worker('worker.js');
    worker.postMessage('开始计算');
    
    worker.onmessage = function(event) {
        console.log('收到结果:', event.data);
    };
    
    worker.onerror = function(error) {
        console.error('Worker错误:', error);
    };
    </script>
    

    worker.js 文件:

    // worker.js
    onmessage = function(event) {
        const result = heavyCalculation();
        postMessage(result);
    };
    
    function heavyCalculation() {
        // 耗时计算
        return '计算结果';
    }
    
  2. WebSockets

    <script>
    const socket = new WebSocket('wss://echo.websocket.org');
    
    socket.onopen = function(event) {
        console.log('连接已打开');
        socket.send('Hello Server!');
    };
    
    socket.onmessage = function(event) {
        console.log('收到消息:', event.data);
    };
    
    socket.onclose = function(event) {
        console.log('连接已关闭:', event.code, event.reason);
    };
    
    socket.onerror = function(error) {
        console.log('WebSocket错误:', error);
    };
    </script>
    

十、响应式设计

10.1 视口设置

<!-- 基础视口 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">

<!-- 完整视口控制 -->
<meta name="viewport" content="
    width=device-width,
    initial-scale=1.0,
    maximum-scale=5.0,
    minimum-scale=0.5,
    user-scalable=yes,
    viewport-fit=cover
">

10.2 响应式图片

<!-- srcset 和 sizes -->
<img src="image-small.jpg"
     srcset="image-small.jpg 320w,
             image-medium.jpg 768w,
             image-large.jpg 1200w"
     sizes="(max-width: 768px) 100vw,
            (max-width: 1200px) 50vw,
            33vw"
     alt="响应式图片">

<!-- picture元素 -->
<picture>
    <source media="(min-width: 1200px)" srcset="large.jpg">
    <source media="(min-width: 768px)" srcset="medium.jpg">
    <source media="(min-width: 320px)" srcset="small.jpg">
    <img src="fallback.jpg" alt="回退图片">
</picture>

<!-- 艺术方向 -->
<picture>
    <source media="(orientation: portrait)" srcset="portrait.jpg">
    <source media="(orientation: landscape)" srcset="landscape.jpg">
    <img src="default.jpg" alt="艺术方向图片">
</picture>

10.3 响应式表格

<!-- 水平滚动 -->
<div style="overflow-x: auto;">
    <table>
        <!-- 宽表格内容 -->
    </table>
</div>

<!-- 重构表格 -->
<table>
    <tr>
        <td data-label="姓名">张三</td>
        <td data-label="年龄">25</td>
        <td data-label="城市">北京</td>
    </tr>
    <!-- 更多行 -->
</table>

<!-- 卡片式表格 -->
<div class="card-table">
    <div class="card">
        <div class="card-header">张三</div>
        <div class="card-content">
            <p><strong>年龄:</strong>25</p>
            <p><strong>城市:</strong>北京</p>
        </div>
    </div>
</div>

10.4 响应式视频

<!-- 视频容器 -->
<div class="video-container">
    <video controls>
        <source src="video.mp4" type="video/mp4">
    </video>
</div>

<style>
.video-container {
    position: relative;
    padding-bottom: 56.25%; /* 16:9 宽高比 */
    height: 0;
    overflow: hidden;
}
.video-container video {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}
</style>

10.5 响应式框架

<!-- Bootstrap网格示例 -->
<div class="container">
    <div class="row">
        <div class="col-12 col-md-6 col-lg-4">
            <div class="card">内容1</div>
        </div>
        <div class="col-12 col-md-6 col-lg-4">
            <div class="card">内容2</div>
        </div>
        <div class="col-12 col-md-12 col-lg-4">
            <div class="card">内容3</div>
        </div>
    </div>
</div>

十一、性能优化

11.1 加载优化

<!-- 异步加载 -->
<script src="script.js" async></script>

<!-- 延迟加载 -->
<script src="script.js" defer></script>

<!-- 模块加载 -->
<script type="module" src="module.js"></script>

<!-- 预加载关键资源 -->
<link rel="preload" href="critical.css" as="style">
<link rel="preload" href="critical.js" as="script">

<!-- 预连接 -->
<link rel="preconnect" href="https://fonts.gstatic.com">

<!-- 懒加载图片 -->
<img src="placeholder.jpg" data-src="image.jpg" loading="lazy" alt="懒加载图片">

<!-- 懒加载iframe -->
<iframe src="about:blank" data-src="content.html" loading="lazy"></iframe>

11.2 资源优化

<!-- 图片优化 -->
<picture>
    <source type="image/webp" srcset="image.webp">
    <source type="image/avif" srcset="image.avif">
    <img src="image.jpg" alt="优化图片">
</picture>

<!-- 字体优化 -->
<link rel="preload" href="font.woff2" as="font" type="font/woff2" crossorigin>
<style>
@font-face {
    font-family: 'MyFont';
    src: url('font.woff2') format('woff2'),
         url('font.woff') format('woff');
    font-display: swap;
}
</style>

<!-- CSS优化 -->
<link rel="stylesheet" href="critical.css" media="all">
<link rel="stylesheet" href="non-critical.css" media="print" onload="this.media='all'">

<!-- JavaScript优化 -->
<script>
// 代码分割
import('./module.js').then(module => {
    module.init();
});
</script>

11.3 缓存策略

<!-- Service Worker缓存 -->
<script>
if ('serviceWorker' in navigator) {
    navigator.serviceWorker.register('/sw.js');
}
</script>

<!-- 资源版本控制 -->
<link rel="stylesheet" href="styles.css?v=1.0.0">
<script src="app.js?v=1.0.0"></script>

<!-- CDN资源 -->
<script src="https://cdn.example.com/jquery.min.js" 
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>

十二、可访问性

12.1 ARIA属性

<!-- 地标角色 -->
<header role="banner">
<nav role="navigation" aria-label="主导航">
<main role="main">
<aside role="complementary">
<footer role="contentinfo">

<!-- 控件角色 -->
<button role="button" aria-label="关闭">
<div role="button" tabindex="0" onclick="...">自定义按钮</div>

<!-- 状态属性 -->
<button aria-pressed="true">已选择</button>
<div aria-hidden="true">屏幕阅读器不可见</div>
<div aria-live="polite">动态更新内容</div>

<!-- 关系属性 -->
<label for="search">搜索</label>
<input id="search" aria-describedby="search-help">
<p id="search-help">输入关键词进行搜索</p>

<!-- 复杂组件 -->
<div role="tablist">
    <button role="tab" aria-selected="true" aria-controls="panel1">选项卡1</button>
    <button role="tab" aria-selected="false" aria-controls="panel2">选项卡2</button>
</div>
<div role="tabpanel" id="panel1">内容1</div>
<div role="tabpanel" id="panel2" hidden>内容2</div>

12.2 键盘导航

<!-- Tab顺序 -->
<div tabindex="0">可聚焦元素</div>
<div tabindex="-1">可编程聚焦</div>
<div tabindex="1">显式顺序(不推荐)</div>

<!-- 跳过导航 -->
<a href="#main" class="skip-link">跳过导航</a>
<main id="main">主要内容</main>

<!-- 键盘事件 -->
<script>
document.addEventListener('keydown', function(event) {
    if (event.key === 'Escape') {
        closeModal();
    }
    if (event.key === 'Enter' || event.key === ' ') {
        activateButton();
    }
});
</script>

12.3 语义化结构

<!-- 正确使用标题 -->
<h1>页面标题</h1>
<h2>章节标题</h2>
<h3>子章节标题</h3>

<!-- 列表语义 -->
<ul role="list">
    <li role="listitem">项目1</li>
    <li role="listitem">项目2</li>
</ul>

<!-- 表格语义 -->
<table>
    <caption>表格标题</caption>
    <thead>
        <tr>
            <th scope="col">列1</th>
            <th scope="col">列2</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <th scope="row">行1</th>
            <td>数据</td>
        </tr>
    </tbody>
</table>

十三、安全

13.1 内容安全

<!-- CSP策略 -->
<meta http-equiv="Content-Security-Policy" 
      content="default-src 'self'; 
               script-src 'self' https://trusted.com;
               style-src 'self' 'unsafe-inline';
               img-src 'self' data: https:;
               font-src 'self'">

<!-- 安全头部 -->
<meta http-equiv="X-Content-Type-Options" content="nosniff">
<meta http-equiv="X-Frame-Options" content="DENY">
<meta http-equiv="Referrer-Policy" content="no-referrer-when-downgrade">

<!-- 安全表单 -->
<form>
    <input type="hidden" name="csrf_token" value="abc123">
    <input type="text" name="data" pattern="[A-Za-z0-9]+">
</form>

13.2 安全资源

<!-- 安全链接 -->
<a href="https://secure.example.com">安全网站</a>

<!-- 资源完整性 -->
<script src="https://code.jquery.com/jquery.min.js"
        integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
        crossorigin="anonymous"></script>

<!-- 安全iframe -->
<iframe src="https://trusted.com" 
        sandbox="allow-scripts allow-same-origin"
        allow="camera 'none'; microphone 'none'">
</iframe>

十四、最佳实践

14.1 代码规范

  1. 结构规范
    • 使用语义化标签
    • 正确嵌套元素
    • 避免div滥用
    • 适当使用注释
  2. 命名规范
    • 有意义的id和class
    • 使用BEM或其他命名约定
    • 保持一致性
  3. 格式规范
    • 缩进一致
    • 属性顺序
    • 引号统一
    • 行长度限制

14.2 性能最佳实践

  1. 减少HTTP请求
  2. 压缩资源
  3. 使用CDN
  4. 启用缓存
  5. 优化图片
  6. 减少重排重绘

14.3 可维护性

  1. 模块化结构
  2. 组件化思维
  3. 文档完善
  4. 版本控制
  5. 自动化测试

14.4 浏览器兼容

  1. 渐进增强
  2. 优雅降级
  3. 特性检测
  4. polyfill使用
  5. 前缀处理

十五、学习资源

15.1 官方文档

  • MDN Web Docs:最权威的Web技术文档
  • WHATWG:HTML Living Standard
  • W3C:Web标准组织
  • Can I Use:浏览器兼容性查询

15.2 在线教程

  • freeCodeCamp:免费编程课程
  • Codecademy:互动式学习
  • W3Schools:入门教程
  • Udemy/Coursera:付费课程

15.3 工具资源

  • VS Code:代码编辑器
  • Chrome DevTools:开发者工具
  • WebPageTest:性能测试
  • Lighthouse:网站质量审计
  • Validator:HTML验证

15.4 社区论坛

  • Stack Overflow:问题解答
  • GitHub:开源项目
  • Dev.to:开发者社区
  • 掘金/思否:中文社区

15.5 进阶方向

  1. CSS深入学习
  2. JavaScript精通
  3. 前端框架(React、Vue、Angular)
  4. 工程化(Webpack、Vite)
  5. 性能优化
  6. TypeScript
  7. PWA
  8. Web组件

15.6 实践项目

  1. 个人博客
  2. 电商网站
  3. 管理系统
  4. 数据可视化
  5. 游戏开发
  6. 移动Web应用

Tags:

Categories:

Updated: