第 2 章 · 文本、链接与多媒体
本章目标:掌握文本语义标签、超链接与路径规则;正确使用图片(alt、尺寸、懒加载、格式优化);嵌入音视频;理解外链安全 rel;在 academy-demo 完成导航、课程封面与介绍媒体。
学时建议:2 小时(含 45 分钟跟练与自检)
前置:第 1 章;已创建 academy-demo 的 index.html 骨架。
2.1 文本相关标签
| 标签 | 说明 | 场景 |
|---|
<span> | 无语义行内容器 | 价格、标签 |
<br> | 换行 | 地址(勿撑布局) |
<blockquote> | 引用块 | 学员评价 |
<code> / <pre> | 行内/多行代码 | API 示例 |
<cite> | 作品名 | 课程、书名 |
<abbr title> | 缩写 | HTML 全称 |
<mark> | 高亮 | 搜索命中 |
<p>课程价:<span class="price">¥199</span></p>
<blockquote>
<p>两周完成 academy-demo 很有成就感。</p>
<footer>— 学员 <cite>小林</cite></footer>
</blockquote>
<p>使用 <code>document.querySelector('nav')</code> 选中导航。</p>
2.2 超链接 <a>
<!-- 站外:新标签 + 安全 rel -->
<a href="https://www.xianzimall.com" target="_blank" rel="noopener noreferrer">
贤紫优选官网
</a>
<!-- 站内 -->
<a href="courses.html">课程列表</a>
<a href="/register.html">立即报名</a>
<!-- 锚点 -->
<a href="#hot-courses">跳到热门课程</a>
<!-- 邮件/电话/下载 -->
<a href="mailto:academy@xianzimall.com">邮件咨询</a>
<a href="assets/syllabus.pdf" download="大纲.pdf">下载大纲</a>
| 属性 | 作用 |
|---|
href | 目标 URL、锚点、mailto、tel |
target="_blank" | 新标签打开 |
rel="noopener" | 防 tabnabbing(与 _blank 配套) |
rel="noreferrer" | 不发送 Referer;多数浏览器隐含 noopener |
rel="nofollow" | SEO:不传递权重(UGC/广告) |
download | 触发下载 |
2.2.1 外链安全 rel 详解
target="_blank" 时新页可通过 window.opener 篡改原页。站外链接默认:
<a href="https://example.com" target="_blank" rel="noopener noreferrer">外链</a>
rel 值 | 效果 |
|---|
noopener | 切断 opener,防 tabnabbing |
noreferrer | 隐藏来源 URL |
nofollow / sponsored / ugc | SEO 标记 |
2.3 路径:相对、根相对与绝对
academy-demo/
├── index.html
├── courses/
│ └── frontend-web.html
└── assets/
├── logo.svg
└── banners/hero.webp
| 类型 | 示例(自 index.html) | 场景 |
|---|
| 绝对 URL | https://cdn.xianzi.com/a.png | CDN |
| 根相对 | /assets/logo.svg | 站内任意深度 |
| 相对同级 | courses.html | 同目录 |
| 相对子级 | assets/banners/hero.webp | 子文件夹 |
| 相对上级 | ../assets/logo.svg | 从 courses/ 回退 |
<!-- courses/frontend-web.html 引用 logo -->
<img src="/assets/logo.svg" alt="贤紫技术学院">
<!-- 或 -->
<img src="../assets/logo.svg" alt="贤紫技术学院">
| 场景 | 推荐 |
|---|
| 有 Web 服务器 | 根相对 /assets/... |
| 本地双击打开 | 相对路径 |
| 部署子路径 | <base href> 或构建工具 |
2.4 图片 <img> 与优化
<img
src="assets/banners/hero.webp"
srcset="assets/banners/hero-640.webp 640w,
assets/banners/hero-1280.webp 1280w"
sizes="(max-width: 768px) 100vw, 1200px"
alt="贤紫技术学院前端课程"
width="1200" height="400"
loading="lazy"
decoding="async"
>
| 属性 | 专业实践 |
|---|
alt | 必填;装饰图 alt="" |
width/height | 防 CLS 布局偏移 |
loading="lazy" | 非首屏图、列表缩略图 |
srcset+sizes | 响应式多分辨率 |
| 格式 | WebP/AVIF > JPEG > PNG |