活动公告

系统通知
05-18 21:22
系统通知
通知:本站资源由网友上传分享,如有违规等问题请到版务模块进行投诉,资源失效请在帖子内回复要求补档,会尽快处理!
10-23 09:31

轻松掌握HTML5和CSS3创建精美响应式网页的实战教程从基础语法到高级应用全面覆盖适合初学者和进阶开发者包含最新特性和行业最佳实践

SunJu_FaceMall

3万

主题

2860

科技点

3万

积分

白金月票

碾压王

积分
32872

塔罗立华奏

<font color=白金月票" /> 发表于 2025-9-17 09:40:05 | 显示全部楼层 |阅读模式

马上注册,结交更多好友,享用更多功能,让你轻松玩转社区。

您需要 登录 才可以下载或查看,没有账号?立即注册

x
引言

在当今数字化时代,网页开发已成为一项不可或缺的技能。HTML5和CSS3作为现代网页开发的基石,为开发者提供了强大的工具来创建美观、功能丰富且适应各种设备的网站。响应式网页设计更是成为了行业标准,确保网站在桌面、平板和手机等各种设备上都能提供优质的用户体验。

本教程将带您从HTML5和CSS3的基础语法开始,逐步深入到高级应用,全面覆盖创建精美响应式网页所需的知识和技能。无论您是刚入门的初学者,还是希望提升技能的进阶开发者,本教程都将为您提供实用的指导和最新的行业最佳实践。

HTML5基础

HTML5简介

HTML5是超文本标记语言的第五个主要版本,它引入了许多新的语义元素、API和多媒体支持,使网页开发更加灵活和强大。与之前的HTML版本相比,HTML5更加注重语义化、可访问性和移动设备支持。

基本文档结构

一个标准的HTML5文档结构如下:
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <title>网页标题</title>
  7.     <link rel="stylesheet" href="styles.css">
  8. </head>
  9. <body>
  10.     <!-- 页面内容 -->
  11. </body>
  12. </html>
复制代码

这里的关键点:

• <!DOCTYPE html>声明文档类型为HTML5
• <html lang="zh-CN">指定页面语言为中文
• <meta charset="UTF-8">指定字符编码为UTF-8
• <meta name="viewport" content="width=device-width, initial-scale=1.0">确保页面在移动设备上正确显示

HTML5语义化标签

HTML5引入了许多语义化标签,使页面结构更加清晰,有助于SEO和可访问性:
  1. <header>
  2.     <h1>网站标题</h1>
  3.     <nav>
  4.         <ul>
  5.             <li><a href="#">首页</a></li>
  6.             <li><a href="#">关于</a></li>
  7.             <li><a href="#">服务</a></li>
  8.             <li><a href="#">联系</a></li>
  9.         </ul>
  10.     </nav>
  11. </header>
  12. <main>
  13.     <section>
  14.         <h2>文章标题</h2>
  15.         <article>
  16.             <p>文章内容...</p>
  17.         </article>
  18.     </section>
  19.    
  20.     <aside>
  21.         <h3>侧边栏</h3>
  22.         <p>侧边栏内容...</p>
  23.     </aside>
  24. </main>
  25. <footer>
  26.     <p>&copy; 2023 版权所有</p>
  27. </footer>
复制代码

这些语义化标签包括:

• <header>:页面或区域的头部
• <nav>:导航链接
• <main>:页面的主要内容
• <section>:文档中的独立区域
• <article>:独立的内容块
• <aside>:侧边栏或相关内容
• <footer>:页面或区域的底部

HTML5表单增强

HTML5为表单提供了许多新的输入类型和属性,使表单验证更加简单:
  1. <form>
  2.     <div>
  3.         <label for="email">电子邮件:</label>
  4.         <input type="email" id="email" name="email" required placeholder="请输入您的邮箱">
  5.     </div>
  6.    
  7.     <div>
  8.         <label for="url">网站:</label>
  9.         <input type="url" id="url" name="url" placeholder="https://example.com">
  10.     </div>
  11.    
  12.     <div>
  13.         <label for="tel">电话:</label>
  14.         <input type="tel" id="tel" name="tel" pattern="[0-9]{3}-[0-9]{4}-[0-9]{4}" placeholder="123-4567-8901">
  15.     </div>
  16.    
  17.     <div>
  18.         <label for="date">日期:</label>
  19.         <input type="date" id="date" name="date">
  20.     </div>
  21.    
  22.     <div>
  23.         <label for="range">范围:</label>
  24.         <input type="range" id="range" name="range" min="0" max="100" value="50">
  25.         <span id="rangeValue">50</span>
  26.     </div>
  27.    
  28.     <div>
  29.         <label for="message">留言:</label>
  30.         <textarea id="message" name="message" rows="4" cols="50" required></textarea>
  31.     </div>
  32.    
  33.     <button type="submit">提交</button>
  34. </form>
复制代码

HTML5新增的输入类型包括:

• email:电子邮件地址
• url:网址
• tel:电话号码
• date:日期选择器
• time:时间选择器
• datetime-local:日期和时间选择器
• month:月份选择器
• week:周选择器
• number:数字输入
• range:范围滑块
• color:颜色选择器
• search:搜索字段

HTML5多媒体支持

HTML5原生支持音频和视频,无需第三方插件:
  1. <!-- 视频示例 -->
  2. <video width="640" height="360" controls poster="poster.jpg">
  3.     <source src="movie.mp4" type="video/mp4">
  4.     <source src="movie.webm" type="video/webm">
  5.     <track kind="subtitles" src="subtitles_en.vtt" srclang="en" label="English">
  6.     <track kind="subtitles" src="subtitles_zh.vtt" srclang="zh" label="中文">
  7.     您的浏览器不支持视频标签。
  8. </video>
  9. <!-- 音频示例 -->
  10. <audio controls>
  11.     <source src="audio.mp3" type="audio/mpeg">
  12.     <source src="audio.ogg" type="audio/ogg">
  13.     您的浏览器不支持音频标签。
  14. </audio>
复制代码

CSS3基础

CSS3简介

CSS3是层叠样式表的第三个主要版本,它引入了许多强大的新特性,如圆角、阴影、渐变、动画和变换等,使网页设计更加灵活和富有创意。

CSS选择器

CSS3提供了更多强大的选择器,使元素选择更加精确:
  1. /* 属性选择器 */
  2. a[href^="https"] { color: green; } /* 选择href属性以https开头的a元素 */
  3. a[href$=".pdf"] { color: red; } /* 选择href属性以.pdf结尾的a元素 */
  4. a[href*="example"] { color: blue; } /* 选择href属性包含example的a元素 */
  5. /* 伪类选择器 */
  6. li:first-child { font-weight: bold; } /* 选择第一个li元素 */
  7. li:last-child { font-style: italic; } /* 选择最后一个li元素 */
  8. li:nth-child(odd) { background: #f0f0f0; } /* 选择奇数位置的li元素 */
  9. li:nth-child(even) { background: #ffffff; } /* 选择偶数位置的li元素 */
  10. li:nth-child(3n) { color: purple; } /* 选择每第三个li元素 */
  11. /* 伪元素选择器 */
  12. p::first-line { font-weight: bold; } /* 选择p元素的第一行 */
  13. p::first-letter { font-size: 200%; } /* 选择p元素的第一个字母 */
  14. p::before { content: ">> "; color: gray; } /* 在p元素前插入内容 */
  15. p::after { content: " <<"; color: gray; } /* 在p元素后插入内容 */
复制代码

CSS3盒模型

CSS3引入了box-sizing属性,使盒模型计算更加灵活:
  1. /* 标准盒模型(默认) */
  2. .element {
  3.     width: 300px;
  4.     padding: 20px;
  5.     border: 5px solid #333;
  6.     margin: 10px;
  7.     /* 总宽度 = width + padding + border = 300 + 40 + 10 = 350px */
  8. }
  9. /* 替代(IE)盒模型 */
  10. .element {
  11.     box-sizing: border-box;
  12.     width: 300px;
  13.     padding: 20px;
  14.     border: 5px solid #333;
  15.     margin: 10px;
  16.     /* 总宽度 = width = 300px(padding和border包含在width内) */
  17. }
  18. /* 全局使用border-box */
  19. * {
  20.     box-sizing: border-box;
  21. }
复制代码

CSS3颜色和背景

CSS3提供了更多颜色和背景选项:
  1. /* RGBA颜色 */
  2. .color-rgba {
  3.     color: rgba(255, 0, 0, 0.7); /* 红色,70%不透明度 */
  4.     background-color: rgba(0, 0, 255, 0.3); /* 蓝色,30%不透明度 */
  5. }
  6. /* HSLA颜色 */
  7. .color-hsla {
  8.     color: hsla(120, 100%, 50%, 0.8); /* 绿色,80%不透明度 */
  9.     background-color: hsla(240, 100%, 50%, 0.5); /* 蓝色,50%不透明度 */
  10. }
  11. /* 线性渐变 */
  12. .gradient-linear {
  13.     background: linear-gradient(to right, #ff0000, #0000ff);
  14.     background: linear-gradient(45deg, #ff0000, #ffff00, #00ff00, #00ffff, #0000ff, #ff00ff, #ff0000);
  15. }
  16. /* 径向渐变 */
  17. .gradient-radial {
  18.     background: radial-gradient(circle, #ff0000, #0000ff);
  19.     background: radial-gradient(ellipse at center, #ff0000 0%, #ffff00 25%, #00ff00 50%, #00ffff 75%, #0000ff 100%);
  20. }
  21. /* 多重背景 */
  22. .multiple-backgrounds {
  23.     background-image: url('image1.png'), url('image2.png');
  24.     background-position: right bottom, left top;
  25.     background-repeat: no-repeat, repeat;
  26. }
复制代码

CSS3文本效果

CSS3提供了更多文本效果选项:
  1. /* 文本阴影 */
  2. .text-shadow {
  3.     text-shadow: 2px 2px 4px rgba(0, 0, 0, 0.5);
  4.     text-shadow: 0 0 3px #ff0000, 0 0 5px #0000ff; /* 多重阴影 */
  5. }
  6. /* 文本溢出处理 */
  7. .text-overflow {
  8.     width: 200px;
  9.     white-space: nowrap;
  10.     overflow: hidden;
  11.     text-overflow: ellipsis; /* 显示省略号 */
  12. }
  13. /* 文字换行 */
  14. .word-wrap {
  15.     width: 200px;
  16.     word-wrap: break-word; /* 允许长单词或URL地址换行 */
  17.     word-break: break-all; /* 允许在单词内换行 */
  18. }
  19. /* 字体调整 */
  20. .font-adjustment {
  21.     font-size: 16px;
  22.     font-size: 1rem; /* 相对于根元素字体大小 */
  23.     font-size: 1.2em; /* 相对于父元素字体大小 */
  24.     font-size: 1.2vw; /* 相于视口宽度的1.2% */
  25.     font-size: calc(16px + 1vw); /* 计算值 */
  26. }
复制代码

响应式设计原理

视口设置

响应式设计的第一步是正确设置视口:
  1. <meta name="viewport" content="width=device-width, initial-scale=1.0">
复制代码

这个meta标签告诉浏览器:

• width=device-width:将视口宽度设置为设备宽度
• initial-scale=1.0:设置初始缩放比例为1.0

其他可选参数:

• minimum-scale:最小缩放比例
• maximum-scale:最大缩放比例
• user-scalable:是否允许用户缩放(yes/no)

媒体查询

媒体查询是响应式设计的核心,它允许我们根据设备特性应用不同的样式:
  1. /* 基本媒体查询语法 */
  2. @media mediatype and|not|only (media feature) {
  3.     CSS-Code;
  4. }
  5. /* 常用媒体类型 */
  6. @media screen { /* 适用于屏幕设备 */ }
  7. @media print { /* 适用于打印设备 */ }
  8. @media speech { /* 适用于语音合成器 */ }
  9. /* 常用媒体特性 */
  10. @media (max-width: 600px) { /* 视口宽度小于等于600px */ }
  11. @media (min-width: 601px) { /* 视口宽度大于等于601px */ }
  12. @media (min-width: 601px) and (max-width: 1200px) { /* 视口宽度在601px到1200px之间 */ }
  13. @media (orientation: portrait) { /* 竖屏方向 */ }
  14. @media (orientation: landscape) { /* 横屏方向 */ }
  15. @media (hover: hover) { /* 设备支持悬停 */ }
  16. @media (hover: none) { /* 设备不支持悬停 */ }
  17. @media (pointer: coarse) { /* 触摸屏设备 */ }
  18. @media (pointer: fine) { /* 精确指针设备(如鼠标) */ }
复制代码

流式布局

流式布局使用相对单位(如百分比)而不是固定单位(如像素),使布局能够根据视口大小自动调整:
  1. .container {
  2.     width: 90%; /* 容器宽度为视口宽度的90% */
  3.     max-width: 1200px; /* 最大宽度限制 */
  4.     margin: 0 auto; /* 居中显示 */
  5. }
  6. .column {
  7.     float: left;
  8.     width: 33.333%; /* 三列等宽布局 */
  9.     padding: 15px;
  10.     box-sizing: border-box; /* 确保padding包含在宽度内 */
  11. }
  12. /* 在小屏幕上改为单列布局 */
  13. @media (max-width: 768px) {
  14.     .column {
  15.         float: none;
  16.         width: 100%;
  17.     }
  18. }
复制代码

弹性图片

确保图片能够根据容器大小自动调整:
  1. img {
  2.     max-width: 100%; /* 图片最大宽度不超过容器宽度 */
  3.     height: auto; /* 高度自动调整,保持宽高比 */
  4. }
  5. /* 背景图片响应式处理 */
  6. .hero {
  7.     background-image: url('large-image.jpg');
  8.     background-size: cover; /* 覆盖整个容器 */
  9.     background-position: center; /* 居中显示 */
  10.     background-repeat: no-repeat; /* 不重复 */
  11. }
  12. /* 使用picture元素提供不同分辨率的图片 */
  13. <picture>
  14.     <source media="(max-width: 768px)" srcset="small-image.jpg">
  15.     <source media="(max-width: 1200px)" srcset="medium-image.jpg">
  16.     <img src="large-image.jpg" alt="描述性文本">
  17. </picture>
复制代码

响应式布局技术

Flexbox布局

Flexbox(弹性盒子)是一种一维布局方法,非常适合用于创建灵活的响应式布局:
  1. /* Flex容器 */
  2. .flex-container {
  3.     display: flex; /* 创建flex容器 */
  4.     flex-direction: row; /* 主轴方向:row(默认)、row-reverse、column、column-reverse */
  5.     flex-wrap: wrap; /* 换行:nowrap(默认)、wrap、wrap-reverse */
  6.     justify-content: space-between; /* 主轴对齐:flex-start(默认)、flex-end、center、space-between、space-around、space-evenly */
  7.     align-items: center; /* 交叉轴对齐:stretch(默认)、flex-start、flex-end、center、baseline */
  8.     align-content: space-between; /* 多行对齐:stretch(默认)、flex-start、flex-end、center、space-between、space-around */
  9.     gap: 20px; /* 项目之间的间距 */
  10. }
  11. /* Flex项目 */
  12. .flex-item {
  13.     flex-grow: 1; /* 放大比例:0(默认,不放大) */
  14.     flex-shrink: 1; /* 缩小比例:1(默认,可以缩小) */
  15.     flex-basis: 0; /* 基准值:auto(默认,项目本身大小) */
  16.     flex: 1 1 0; /* 简写:flex-grow flex-shrink flex-basis */
  17.     align-self: center; /* 单个项目对齐:auto(默认)、flex-start、flex-end、center、baseline、stretch */
  18.     order: 1; /* 排序顺序:0(默认),数值越小越靠前 */
  19. }
  20. /* 实际应用示例 */
  21. .navbar {
  22.     display: flex;
  23.     justify-content: space-between;
  24.     align-items: center;
  25.     padding: 1rem;
  26. }
  27. .logo {
  28.     flex: 0 0 auto;
  29. }
  30. .nav-links {
  31.     display: flex;
  32.     gap: 1rem;
  33. }
  34. @media (max-width: 768px) {
  35.     .navbar {
  36.         flex-direction: column;
  37.     }
  38.    
  39.     .nav-links {
  40.         flex-direction: column;
  41.         width: 100%;
  42.         text-align: center;
  43.     }
  44. }
复制代码

Grid布局

Grid(网格)是一种二维布局方法,非常适合创建复杂的响应式布局:
  1. /* Grid容器 */
  2. .grid-container {
  3.     display: grid; /* 创建grid容器 */
  4.     grid-template-columns: repeat(3, 1fr); /* 定义列:3列,每列等宽 */
  5.     grid-template-rows: auto 200px; /* 定义行:第一行自动高度,第二行200px高 */
  6.     grid-template-areas:
  7.         "header header header"
  8.         "sidebar main main"
  9.         "footer footer footer"; /* 定义网格区域 */
  10.     grid-gap: 20px; /* 网格间距 */
  11.     justify-items: center; /* 水平对齐:stretch(默认)、start、end、center */
  12.     align-items: center; /* 垂直对齐:stretch(默认)、start、end、center */
  13. }
  14. /* Grid项目 */
  15. .grid-item {
  16.     grid-column: 1 / 3; /* 列位置:从第1条线到第3条线 */
  17.     grid-row: 2 / 4; /* 行位置:从第2条线到第4条线 */
  18.     grid-area: main; /* 指定网格区域名称 */
  19.     justify-self: center; /* 单个项目水平对齐 */
  20.     align-self: center; /* 单个项目垂直对齐 */
  21. }
  22. /* 响应式Grid布局 */
  23. .responsive-grid {
  24.     display: grid;
  25.     grid-template-columns: repeat(auto-fit, minmax(250px, 1fr)); /* 自动适应,最小250px,最大等分 */
  26.     grid-gap: 20px;
  27. }
  28. /* 实际应用示例 */
  29. .page-layout {
  30.     display: grid;
  31.     grid-template-areas:
  32.         "header header header"
  33.         "sidebar main main"
  34.         "footer footer footer";
  35.     grid-template-columns: 200px 1fr 1fr;
  36.     grid-template-rows: auto 1fr auto;
  37.     min-height: 100vh;
  38.     gap: 20px;
  39. }
  40. .header {
  41.     grid-area: header;
  42. }
  43. .sidebar {
  44.     grid-area: sidebar;
  45. }
  46. .main {
  47.     grid-area: main;
  48. }
  49. .footer {
  50.     grid-area: footer;
  51. }
  52. @media (max-width: 768px) {
  53.     .page-layout {
  54.         grid-template-areas:
  55.             "header"
  56.             "main"
  57.             "sidebar"
  58.             "footer";
  59.         grid-template-columns: 1fr;
  60.         grid-template-rows: auto auto auto auto;
  61.     }
  62. }
复制代码

多列布局

CSS3的多列布局适合用于文本内容:
  1. /* 多列布局 */
  2. .columns {
  3.     column-count: 3; /* 列数 */
  4.     column-width: 200px; /* 列宽 */
  5.     column-gap: 30px; /* 列间距 */
  6.     column-rule: 1px solid #ddd; /* 列之间的分隔线 */
  7.     column-fill: balance; /* 内容平衡:balance(默认,平衡各列高度)、auto(按顺序填充) */
  8. }
  9. /* 跨列 */
  10. .heading {
  11.     column-span: all; /* 跨所有列 */
  12.     text-align: center;
  13. }
  14. /* 响应式多列布局 */
  15. @media (max-width: 768px) {
  16.     .columns {
  17.         column-count: 2;
  18.     }
  19. }
  20. @media (max-width: 480px) {
  21.     .columns {
  22.         column-count: 1;
  23.     }
  24. }
复制代码

CSS3高级特性

过渡效果

CSS3过渡使属性变化更加平滑:
  1. /* 基本过渡 */
  2. .element {
  3.     width: 100px;
  4.     height: 100px;
  5.     background-color: blue;
  6.     transition: width 2s, height 2s, background-color 2s; /* 多属性过渡 */
  7. }
  8. .element:hover {
  9.     width: 200px;
  10.     height: 200px;
  11.     background-color: red;
  12. }
  13. /* 过渡属性详解 */
  14. .element {
  15.     transition-property: width, height, background-color; /* 指定过渡属性 */
  16.     transition-duration: 2s; /* 过渡持续时间 */
  17.     transition-timing-function: ease; /* 过渡速度曲线:ease(默认)、linear、ease-in、ease-out、ease-in-out、cubic-bezier() */
  18.     transition-delay: 0.5s; /* 过渡延迟时间 */
  19.     transition: width 2s ease 0.5s, height 2s ease 0.5s; /* 简写形式 */
  20. }
  21. /* 实际应用示例 */
  22. .button {
  23.     display: inline-block;
  24.     padding: 10px 20px;
  25.     background-color: #3498db;
  26.     color: white;
  27.     border: none;
  28.     border-radius: 4px;
  29.     cursor: pointer;
  30.     transition: all 0.3s ease;
  31. }
  32. .button:hover {
  33.     background-color: #2980b9;
  34.     transform: translateY(-2px);
  35.     box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  36. }
复制代码

变换效果

CSS3变换允许元素进行旋转、缩放、倾斜和平移:
  1. /* 2D变换 */
  2. .transform-2d {
  3.     transform: translate(50px, 100px); /* 平移:X轴50px,Y轴100px */
  4.     transform: rotate(45deg); /* 旋转:45度 */
  5.     transform: scale(1.5, 0.5); /* 缩放:X轴1.5倍,Y轴0.5倍 */
  6.     transform: skew(30deg, 20deg); /* 倾斜:X轴30度,Y轴20度 */
  7.     transform: matrix(1, 0, 0, 1, 0, 0); /* 矩阵变换 */
  8.     transform: translate(50px, 100px) rotate(45deg) scale(1.5); /* 组合变换 */
  9. }
  10. /* 3D变换 */
  11. .transform-3d {
  12.     transform: translate3d(50px, 100px, 200px); /* 3D平移 */
  13.     transform: rotate3d(1, 1, 1, 45deg); /* 3D旋转 */
  14.     transform: scale3d(1.5, 0.5, 2); /* 3D缩放 */
  15.     transform: perspective(500px) rotateX(45deg); /* 透视和X轴旋转 */
  16.     transform-style: preserve-3d; /* 3D空间 */
  17.     backface-visibility: hidden; /* 背面可见性 */
  18. }
  19. /* 变换原点 */
  20. .transform-origin {
  21.     transform-origin: center center; /* 变换原点:默认中心 */
  22.     transform-origin: top left; /* 左上角 */
  23.     transform-origin: 50% 50%; /* 中心位置 */
  24.     transform-origin: 0 0; /* 左上角 */
  25. }
  26. /* 实际应用示例 */
  27. .card {
  28.     width: 300px;
  29.     height: 200px;
  30.     background-color: #fff;
  31.     border-radius: 8px;
  32.     box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
  33.     transition: transform 0.3s ease;
  34. }
  35. .card:hover {
  36.     transform: translateY(-10px) rotateY(5deg);
  37.     box-shadow: 0 10px 20px rgba(0, 0, 0, 0.2);
  38. }
复制代码

动画效果

CSS3动画允许创建更复杂的动画效果:
  1. /* 基本动画 */
  2. @keyframes slideIn {
  3.     from {
  4.         transform: translateX(-100%);
  5.         opacity: 0;
  6.     }
  7.     to {
  8.         transform: translateX(0);
  9.         opacity: 1;
  10.     }
  11. }
  12. .element {
  13.     animation-name: slideIn; /* 动画名称 */
  14.     animation-duration: 2s; /* 动画持续时间 */
  15.     animation-timing-function: ease; /* 动画速度曲线 */
  16.     animation-delay: 0.5s; /* 动画延迟时间 */
  17.     animation-iteration-count: infinite; /* 动画迭代次数:infinite(无限)、数字 */
  18.     animation-direction: alternate; /* 动画方向:normal(默认)、reverse、alternate、alternate-reverse */
  19.     animation-fill-mode: forwards; /* 动画填充模式:none(默认)、forwards、backwards、both */
  20.     animation-play-state: running; /* 动画播放状态:running(默认)、paused */
  21.     animation: slideIn 2s ease 0.5s infinite alternate forwards; /* 简写形式 */
  22. }
  23. /* 复杂动画示例 */
  24. @keyframes bounce {
  25.     0%, 100% {
  26.         transform: translateY(0);
  27.         animation-timing-function: cubic-bezier(0.8, 0, 1, 1);
  28.     }
  29.     50% {
  30.         transform: translateY(-30px);
  31.         animation-timing-function: cubic-bezier(0, 0, 0.2, 1);
  32.     }
  33. }
  34. @keyframes pulse {
  35.     0% {
  36.         transform: scale(1);
  37.         opacity: 1;
  38.     }
  39.     50% {
  40.         transform: scale(1.1);
  41.         opacity: 0.7;
  42.     }
  43.     100% {
  44.         transform: scale(1);
  45.         opacity: 1;
  46.     }
  47. }
  48. .bouncing-ball {
  49.     width: 50px;
  50.     height: 50px;
  51.     border-radius: 50%;
  52.     background-color: #3498db;
  53.     animation: bounce 1s infinite;
  54. }
  55. .pulsing-heart {
  56.     width: 50px;
  57.     height: 50px;
  58.     background-color: #e74c3c;
  59.     position: relative;
  60.     transform: rotate(45deg);
  61.     animation: pulse 1.5s infinite;
  62. }
  63. .pulsing-heart::before,
  64. .pulsing-heart::after {
  65.     content: '';
  66.     width: 50px;
  67.     height: 50px;
  68.     position: absolute;
  69.     background-color: #e74c3c;
  70.     border-radius: 50%;
  71. }
  72. .pulsing-heart::before {
  73.     top: -25px;
  74.     left: 0;
  75. }
  76. .pulsing-heart::after {
  77.     left: -25px;
  78.     top: 0;
  79. }
复制代码

自定义属性(CSS变量)

CSS变量允许定义可重用的值:
  1. /* 定义变量 */
  2. :root {
  3.     --primary-color: #3498db;
  4.     --secondary-color: #2ecc71;
  5.     --text-color: #333;
  6.     --background-color: #fff;
  7.     --font-size-base: 16px;
  8.     --spacing-unit: 8px;
  9.     --border-radius: 4px;
  10. }
  11. /* 使用变量 */
  12. .button {
  13.     background-color: var(--primary-color);
  14.     color: var(--background-color);
  15.     font-size: var(--font-size-base);
  16.     padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 3);
  17.     border-radius: var(--border-radius);
  18. }
  19. /* 变量作用域 */
  20. .card {
  21.     --card-background: #f8f9fa;
  22.     --card-border-color: #dee2e6;
  23.     background-color: var(--card-background);
  24.     border: 1px solid var(--card-border-color);
  25. }
  26. /* 通过JavaScript修改变量 */
  27. document.documentElement.style.setProperty('--primary-color', '#e74c3c');
  28. /* 媒体查询中的变量 */
  29. @media (prefers-color-scheme: dark) {
  30.     :root {
  31.         --primary-color: #5dade2;
  32.         --secondary-color: #58d68d;
  33.         --text-color: #f8f9fa;
  34.         --background-color: #2c3e50;
  35.     }
  36. }
复制代码

HTML5高级特性

Canvas绘图

Canvas API允许使用JavaScript在网页上绘制图形:
  1. <canvas id="myCanvas" width="400" height="300"></canvas>
  2. <script>
  3.     // 获取canvas元素和上下文
  4.     const canvas = document.getElementById('myCanvas');
  5.     const ctx = canvas.getContext('2d');
  6.     // 绘制矩形
  7.     ctx.fillStyle = '#3498db';
  8.     ctx.fillRect(50, 50, 100, 80);
  9.     // 绘制圆形
  10.     ctx.beginPath();
  11.     ctx.arc(250, 90, 40, 0, Math.PI * 2);
  12.     ctx.fillStyle = '#e74c3c';
  13.     ctx.fill();
  14.     // 绘制线条
  15.     ctx.beginPath();
  16.     ctx.moveTo(50, 200);
  17.     ctx.lineTo(150, 250);
  18.     ctx.lineTo(250, 200);
  19.     ctx.lineTo(350, 250);
  20.     ctx.strokeStyle = '#2ecc71';
  21.     ctx.lineWidth = 3;
  22.     ctx.stroke();
  23.     // 绘制文本
  24.     ctx.font = '20px Arial';
  25.     ctx.fillStyle = '#333';
  26.     ctx.fillText('Hello Canvas!', 150, 30);
  27.     // 绘制图像
  28.     const img = new Image();
  29.     img.src = 'image.jpg';
  30.     img.onload = function() {
  31.         ctx.drawImage(img, 300, 150, 80, 80);
  32.     };
  33.     // 创建渐变
  34.     const gradient = ctx.createLinearGradient(0, 0, 400, 0);
  35.     gradient.addColorStop(0, '#3498db');
  36.     gradient.addColorStop(1, '#9b59b6');
  37.     ctx.fillStyle = gradient;
  38.     ctx.fillRect(50, 150, 200, 30);
  39. </script>
复制代码

SVG图形

SVG(可缩放矢量图形)是一种基于XML的矢量图像格式:
  1. <!-- 基本SVG图形 -->
  2. <svg width="400" height="300" xmlns="http://www.w3.org/2000/svg">
  3.     <!-- 矩形 -->
  4.     <rect x="50" y="50" width="100" height="80" fill="#3498db" rx="10" ry="10" />
  5.    
  6.     <!-- 圆形 -->
  7.     <circle cx="250" cy="90" r="40" fill="#e74c3c" />
  8.    
  9.     <!-- 椭圆 -->
  10.     <ellipse cx="100" cy="200" rx="80" ry="40" fill="#2ecc71" />
  11.    
  12.     <!-- 线条 -->
  13.     <line x1="200" y1="150" x2="350" y2="250" stroke="#f39c12" stroke-width="3" />
  14.    
  15.     <!-- 多边形 -->
  16.     <polygon points="250,150 300,200 200,200" fill="#9b59b6" />
  17.    
  18.     <!-- 路径 -->
  19.     <path d="M50,250 Q100,200 150,250 T250,250" stroke="#1abc9c" stroke-width="3" fill="none" />
  20.    
  21.     <!-- 文本 -->
  22.     <text x="200" y="30" font-family="Arial" font-size="20" fill="#333" text-anchor="middle">Hello SVG!</text>
  23.    
  24.     <!-- 渐变 -->
  25.     <defs>
  26.         <linearGradient id="gradient" x1="0%" y1="0%" x2="100%" y2="0%">
  27.             <stop offset="0%" style="stop-color:#3498db;stop-opacity:1" />
  28.             <stop offset="100%" style="stop-color:#9b59b6;stop-opacity:1" />
  29.         </linearGradient>
  30.     </defs>
  31.     <rect x="50" y="270" width="200" height="20" fill="url(#gradient)" />
  32. </svg>
复制代码

Web存储

HTML5提供了两种客户端存储方式:localStorage和sessionStorage:
  1. <script>
  2.     // localStorage - 持久化存储
  3.     // 存储数据
  4.     localStorage.setItem('username', 'JohnDoe');
  5.     localStorage.setItem('userAge', '30');
  6.    
  7.     // 读取数据
  8.     const username = localStorage.getItem('username');
  9.     const userAge = localStorage.getItem('userAge');
  10.     console.log(username); // 输出: JohnDoe
  11.     console.log(userAge); // 输出: 30
  12.    
  13.     // 删除数据
  14.     localStorage.removeItem('username');
  15.    
  16.     // 清空所有数据
  17.     localStorage.clear();
  18.    
  19.     // 存储对象(需要序列化)
  20.     const user = {
  21.         name: 'John Doe',
  22.         age: 30,
  23.         email: 'john@example.com'
  24.     };
  25.     localStorage.setItem('user', JSON.stringify(user));
  26.    
  27.     // 读取对象(需要反序列化)
  28.     const storedUser = JSON.parse(localStorage.getItem('user'));
  29.     console.log(storedUser.name); // 输出: John Doe
  30.    
  31.     // sessionStorage - 会话级存储(关闭浏览器后清除)
  32.     // 用法与localStorage相同
  33.     sessionStorage.setItem('sessionData', 'This will be cleared after the session ends');
  34.     const sessionData = sessionStorage.getItem('sessionData');
  35.     console.log(sessionData); // 输出: This will be cleared after the session ends
  36.    
  37.     // 监听存储事件(当其他文档修改localStorage时触发)
  38.     window.addEventListener('storage', function(event) {
  39.         console.log('Storage changed:', event.key, event.oldValue, event.newValue);
  40.     });
  41. </script>
复制代码

Web Workers

Web Workers允许在后台运行JavaScript,不阻塞用户界面:
  1. <!-- 主线程代码 -->
  2. <script>
  3.     // 创建Web Worker
  4.     const worker = new Worker('worker.js');
  5.    
  6.     // 向Worker发送消息
  7.     worker.postMessage({
  8.         command: 'calculate',
  9.         data: [1, 2, 3, 4, 5]
  10.     });
  11.    
  12.     // 接收Worker发送的消息
  13.     worker.onmessage = function(event) {
  14.         console.log('Result from worker:', event.data.result);
  15.     };
  16.    
  17.     // 处理Worker错误
  18.     worker.onerror = function(error) {
  19.         console.error('Worker error:', error.message);
  20.     };
  21.    
  22.     // 终止Worker
  23.     // worker.terminate();
  24. </script>
  25. <!-- worker.js 文件内容 -->
  26. // worker.js
  27. self.onmessage = function(event) {
  28.     const command = event.data.command;
  29.     const data = event.data.data;
  30.    
  31.     if (command === 'calculate') {
  32.         // 执行耗时计算
  33.         const result = data.reduce((sum, num) => sum + num, 0);
  34.         
  35.         // 发送结果回主线程
  36.         self.postMessage({
  37.             result: result
  38.         });
  39.     }
  40. };
  41. // 也可以使用importScripts导入其他脚本
  42. // importScripts('helper.js');
复制代码

Geolocation API

Geolocation API允许获取用户的位置信息:
  1. <script>
  2.     // 检查浏览器是否支持Geolocation
  3.     if ('geolocation' in navigator) {
  4.         // 获取当前位置
  5.         navigator.geolocation.getCurrentPosition(
  6.             // 成功回调
  7.             function(position) {
  8.                 const latitude = position.coords.latitude;
  9.                 const longitude = position.coords.longitude;
  10.                 const accuracy = position.coords.accuracy;
  11.                
  12.                 console.log('Latitude:', latitude);
  13.                 console.log('Longitude:', longitude);
  14.                 console.log('Accuracy:', accuracy);
  15.                
  16.                 // 在地图上显示位置
  17.                 const mapUrl = `https://maps.google.com/maps?q=${latitude},${longitude}`;
  18.                 console.log('Map URL:', mapUrl);
  19.             },
  20.             // 错误回调
  21.             function(error) {
  22.                 switch(error.code) {
  23.                     case error.PERMISSION_DENIED:
  24.                         console.error('User denied the request for Geolocation.');
  25.                         break;
  26.                     case error.POSITION_UNAVAILABLE:
  27.                         console.error('Location information is unavailable.');
  28.                         break;
  29.                     case error.TIMEOUT:
  30.                         console.error('The request to get user location timed out.');
  31.                         break;
  32.                     case error.UNKNOWN_ERROR:
  33.                         console.error('An unknown error occurred.');
  34.                         break;
  35.                 }
  36.             },
  37.             // 选项
  38.             {
  39.                 enableHighAccuracy: true, // 高精度模式
  40.                 timeout: 5000, // 超时时间(毫秒)
  41.                 maximumAge: 0 // 缓存时间(毫秒),0表示不使用缓存
  42.             }
  43.         );
  44.         
  45.         // 持续监控位置变化
  46.         const watchId = navigator.geolocation.watchPosition(
  47.             function(position) {
  48.                 console.log('Position updated:', position.coords.latitude, position.coords.longitude);
  49.             },
  50.             function(error) {
  51.                 console.error('Error watching position:', error.message);
  52.             }
  53.         );
  54.         
  55.         // 停止监控
  56.         // navigator.geolocation.clearWatch(watchId);
  57.     } else {
  58.         console.error('Geolocation is not supported by this browser.');
  59.     }
  60. </script>
复制代码

性能优化

图片优化

图片通常是网页中最大的资源,优化图片可以显著提高加载速度:
  1. <!-- 使用适当的图片格式 -->
  2. <!-- JPEG:适合照片 -->
  3. <img src="photo.jpg" alt="照片描述">
  4. <!-- PNG:适合需要透明度的图像 -->
  5. <img src="logo.png" alt="标志描述">
  6. <!-- SVG:适合图标和简单图形 -->
  7. <img src="icon.svg" alt="图标描述">
  8. <!-- WebP:现代格式,提供更好的压缩率 -->
  9. <picture>
  10.     <source srcset="image.webp" type="image/webp">
  11.     <img src="image.jpg" alt="图像描述">
  12. </picture>
  13. <!-- 响应式图片 -->
  14. <img srcset="small.jpg 480w, medium.jpg 768w, large.jpg 1024w"
  15.      sizes="(max-width: 600px) 480px, (max-width: 900px) 768px, 1024px"
  16.      src="medium.jpg" alt="响应式图像">
  17. <!-- 懒加载图片 -->
  18. <img src="placeholder.jpg" data-src="actual-image.jpg" alt="懒加载图像" class="lazyload">
  19. <script>
  20.     // 懒加载实现
  21.     document.addEventListener('DOMContentLoaded', function() {
  22.         const lazyImages = document.querySelectorAll('img.lazyload');
  23.         
  24.         function lazyLoad() {
  25.             lazyImages.forEach(img => {
  26.                 if (img.getBoundingClientRect().top <= window.innerHeight && img.getBoundingClientRect().bottom >= 0 && getComputedStyle(img).display !== 'none') {
  27.                     img.src = img.dataset.src;
  28.                     img.classList.remove('lazyload');
  29.                 }
  30.             });
  31.         }
  32.         
  33.         // 初始加载
  34.         lazyLoad();
  35.         
  36.         // 滚动时加载
  37.         window.addEventListener('scroll', lazyLoad);
  38.         window.addEventListener('resize', lazyLoad);
  39.     });
  40. </script>
  41. <!-- 使用CSS Sprites减少HTTP请求 -->
  42. <style>
  43.     .icon-home {
  44.         width: 16px;
  45.         height: 16px;
  46.         background-image: url('sprite.png');
  47.         background-position: 0 0;
  48.     }
  49.    
  50.     .icon-settings {
  51.         width: 16px;
  52.         height: 16px;
  53.         background-image: url('sprite.png');
  54.         background-position: -16px 0;
  55.     }
  56. </style>
  57. <span class="icon-home"></span>
  58. <span class="icon-settings"></span>
复制代码

代码优化

优化HTML、CSS和JavaScript代码可以提高性能:
  1. <!-- HTML优化 -->
  2. <!-- 减少DOM元素数量 -->
  3. <!-- 避免深层嵌套 -->
  4. <!-- 使用语义化标签 -->
  5. <!-- 避免内联样式和脚本 -->
  6. <!-- CSS优化 -->
  7. <style>
  8.     /* 避免使用@import */
  9.     /* @import url('styles.css'); */
  10.    
  11.     /* 使用<link>代替@import */
  12.     /* <link rel="stylesheet" href="styles.css"> */
  13.    
  14.     /* 压缩CSS */
  15.     /* 移除注释、空格和不必要的字符 */
  16.    
  17.     /* 合并CSS文件 */
  18.     /* 减少HTTP请求 */
  19.    
  20.     /* 使用CSS预处理器(如Sass、Less) */
  21.     /* 提高代码组织和可维护性 */
  22.    
  23.     /* 避免使用昂贵的属性 */
  24.     /* 如box-shadow、border-radius、filter等 */
  25.    
  26.     /* 使用硬件加速 */
  27.     .animated-element {
  28.         transform: translateZ(0);
  29.         will-change: transform;
  30.     }
  31.    
  32.     /* 避免过度使用选择器 */
  33.     /* 而不是:body div.container ul li a */
  34.     /* 使用:.nav-link */
  35. </style>
  36. <!-- JavaScript优化 -->
  37. <script>
  38.     // 压缩JavaScript
  39.     // 移除注释、空格和不必要的字符
  40.     // 缩短变量名
  41.    
  42.     // 延迟加载非关键JavaScript
  43.     // <script src="non-critical.js" defer></script>
  44.     // <script src="non-critical.js" async></script>
  45.    
  46.     // 避免全局变量
  47.     // 使用IIFE或模块模式
  48.     (function() {
  49.         const privateVar = '私有变量';
  50.         
  51.         function privateFunction() {
  52.             console.log(privateVar);
  53.         }
  54.         
  55.         window.publicFunction = function() {
  56.             privateFunction();
  57.         };
  58.     })();
  59.    
  60.     // 使用事件委托减少事件监听器
  61.     document.getElementById('parent').addEventListener('click', function(event) {
  62.         if (event.target.classList.contains('child')) {
  63.             console.log('子元素被点击');
  64.         }
  65.     });
  66.    
  67.     // 避免DOM操作过多
  68.     // 使用文档片段
  69.     const fragment = document.createDocumentFragment();
  70.    
  71.     for (let i = 0; i < 100; i++) {
  72.         const li = document.createElement('li');
  73.         li.textContent = `Item ${i}`;
  74.         fragment.appendChild(li);
  75.     }
  76.    
  77.     document.getElementById('list').appendChild(fragment);
  78.    
  79.     // 使用requestAnimationFrame优化动画
  80.     function animate() {
  81.         // 动画逻辑
  82.         requestAnimationFrame(animate);
  83.     }
  84.    
  85.     requestAnimationFrame(animate);
  86.    
  87.     // 使用防抖和节流优化事件处理
  88.     // 防抖
  89.     function debounce(func, wait) {
  90.         let timeout;
  91.         return function() {
  92.             const context = this;
  93.             const args = arguments;
  94.             clearTimeout(timeout);
  95.             timeout = setTimeout(() => func.apply(context, args), wait);
  96.         };
  97.     }
  98.    
  99.     // 节流
  100.     function throttle(func, limit) {
  101.         let inThrottle;
  102.         return function() {
  103.             const args = arguments;
  104.             const context = this;
  105.             if (!inThrottle) {
  106.                 func.apply(context, args);
  107.                 inThrottle = true;
  108.                 setTimeout(() => inThrottle = false, limit);
  109.             }
  110.         };
  111.     }
  112.    
  113.     // 使用示例
  114.     window.addEventListener('resize', debounce(function() {
  115.         console.log('窗口大小改变');
  116.     }, 200));
  117.    
  118.     window.addEventListener('scroll', throttle(function() {
  119.         console.log('页面滚动');
  120.     }, 100));
  121. </script>
复制代码

缓存策略

利用浏览器缓存可以减少服务器请求,提高页面加载速度:
  1. <!-- 使用HTTP缓存头 -->
  2. <!-- 在服务器配置中设置 -->
  3. <!--
  4. Cache-Control: max-age=31536000, immutable
  5. ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4"
  6. Last-Modified: Wed, 21 Oct 2015 07:28:00 GMT
  7. -->
  8. <!-- 使用Service Worker缓存资源 -->
  9. <script>
  10.     // 注册Service Worker
  11.     if ('serviceWorker' in navigator) {
  12.         window.addEventListener('load', function() {
  13.             navigator.serviceWorker.register('/service-worker.js').then(function(registration) {
  14.                 console.log('ServiceWorker registration successful with scope: ', registration.scope);
  15.             }, function(error) {
  16.                 console.log('ServiceWorker registration failed: ', error);
  17.             });
  18.         });
  19.     }
  20. </script>
  21. <!-- service-worker.js 文件内容 -->
  22. const CACHE_NAME = 'my-site-cache-v1';
  23. const urlsToCache = [
  24.     '/',
  25.     '/styles/main.css',
  26.     '/scripts/main.js',
  27.     '/images/logo.png'
  28. ];
  29. self.addEventListener('install', function(event) {
  30.     // 安装Service Worker并缓存资源
  31.     event.waitUntil(
  32.         caches.open(CACHE_NAME)
  33.             .then(function(cache) {
  34.                 console.log('Opened cache');
  35.                 return cache.addAll(urlsToCache);
  36.             })
  37.     );
  38. });
  39. self.addEventListener('fetch', function(event) {
  40.     // 拦截网络请求并从缓存中响应
  41.     event.respondWith(
  42.         caches.match(event.request)
  43.             .then(function(response) {
  44.                 // 如果资源在缓存中,则返回缓存的资源
  45.                 if (response) {
  46.                     return response;
  47.                 }
  48.                
  49.                 // 否则发起网络请求
  50.                 return fetch(event.request);
  51.             })
  52.     );
  53. });
  54. self.addEventListener('activate', function(event) {
  55.     // 清理旧缓存
  56.     const cacheWhitelist = [CACHE_NAME];
  57.     event.waitUntil(
  58.         caches.keys().then(function(cacheNames) {
  59.             return Promise.all(
  60.                 cacheNames.map(function(cacheName) {
  61.                     if (cacheWhitelist.indexOf(cacheName) === -1) {
  62.                         return caches.delete(cacheName);
  63.                     }
  64.                 })
  65.             );
  66.         })
  67.     );
  68. });
  69. <!-- 使用localStorage缓存数据 -->
  70. <script>
  71.     // 检查是否有缓存的数据
  72.     const cachedData = localStorage.getItem('cachedData');
  73.    
  74.     if (cachedData) {
  75.         // 使用缓存的数据
  76.         const data = JSON.parse(cachedData);
  77.         console.log('使用缓存的数据:', data);
  78.     } else {
  79.         // 从服务器获取数据
  80.         fetch('https://api.example.com/data')
  81.             .then(response => response.json())
  82.             .then(data => {
  83.                 console.log('从服务器获取的数据:', data);
  84.                
  85.                 // 缓存数据
  86.                 localStorage.setItem('cachedData', JSON.stringify(data));
  87.                
  88.                 // 设置缓存过期时间(例如1小时)
  89.                 localStorage.setItem('cachedDataExpiry', Date.now() + 3600000);
  90.             });
  91.     }
  92.    
  93.     // 检查缓存是否过期
  94.     const expiryTime = localStorage.getItem('cachedDataExpiry');
  95.    
  96.     if (expiryTime && Date.now() > parseInt(expiryTime)) {
  97.         // 缓存已过期,清除缓存
  98.         localStorage.removeItem('cachedData');
  99.         localStorage.removeItem('cachedDataExpiry');
  100.         console.log('缓存已过期,已清除');
  101.     }
  102. </script>
复制代码

最佳实践

代码组织和可维护性

良好的代码组织可以提高可维护性和开发效率:
  1. <!-- HTML最佳实践 -->
  2. <!DOCTYPE html>
  3. <html lang="zh-CN">
  4. <head>
  5.     <meta charset="UTF-8">
  6.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  7.     <meta name="description" content="网站描述">
  8.     <meta name="keywords" content="关键词1, 关键词2">
  9.     <title>网站标题</title>
  10.    
  11.     <!-- 预加载关键资源 -->
  12.     <link rel="preload" href="critical.css" as="style">
  13.     <link rel="preload" href="critical.js" as="script">
  14.    
  15.     <!-- 关键CSS内联 -->
  16.     <style>
  17.         /* 关键渲染路径CSS */
  18.         body {
  19.             font-family: 'Arial', sans-serif;
  20.             line-height: 1.6;
  21.             margin: 0;
  22.             padding: 0;
  23.             color: #333;
  24.         }
  25.         
  26.         .container {
  27.             width: 90%;
  28.             max-width: 1200px;
  29.             margin: 0 auto;
  30.             padding: 20px;
  31.         }
  32.     </style>
  33.    
  34.     <!-- 非关键CSS异步加载 -->
  35.     <link rel="stylesheet" href="non-critical.css" media="print" onload="this.media='all'">
  36.    
  37.     <!-- 字体预加载 -->
  38.     <link rel="preconnect" href="https://fonts.googleapis.com">
  39.     <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  40.     <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700&display=swap" rel="stylesheet">
  41. </head>
  42. <body>
  43.     <!-- 跳转到主要内容链接(提高可访问性) -->
  44.     <a href="#main-content" class="skip-link">跳转到主要内容</a>
  45.    
  46.     <!-- 页面头部 -->
  47.     <header class="header">
  48.         <div class="container">
  49.             <div class="logo">
  50.                 <a href="/">
  51.                     <img src="logo.svg" alt="网站标志">
  52.                 </a>
  53.             </div>
  54.             
  55.             <nav class="main-nav" aria-label="主导航">
  56.                 <button class="nav-toggle" aria-expanded="false" aria-controls="nav-menu">
  57.                     <span class="sr-only">菜单</span>
  58.                     <span class="icon-bar"></span>
  59.                     <span class="icon-bar"></span>
  60.                     <span class="icon-bar"></span>
  61.                 </button>
  62.                
  63.                 <ul id="nav-menu" class="nav-menu">
  64.                     <li><a href="/">首页</a></li>
  65.                     <li><a href="/about">关于</a></li>
  66.                     <li><a href="/services">服务</a></li>
  67.                     <li><a href="/contact">联系</a></li>
  68.                 </ul>
  69.             </nav>
  70.         </div>
  71.     </header>
  72.    
  73.     <!-- 主要内容 -->
  74.     <main id="main-content" class="main-content">
  75.         <div class="container">
  76.             <h1>页面标题</h1>
  77.             
  78.             <section class="content-section">
  79.                 <h2>章节标题</h2>
  80.                 <p>内容段落...</p>
  81.             </section>
  82.         </div>
  83.     </main>
  84.    
  85.     <!-- 页面底部 -->
  86.     <footer class="footer">
  87.         <div class="container">
  88.             <p>&copy; 2023 网站名称. 保留所有权利.</p>
  89.         </div>
  90.     </footer>
  91.    
  92.     <!-- 关键JavaScript内联 -->
  93.     <script>
  94.         // 关键功能JavaScript
  95.         document.addEventListener('DOMContentLoaded', function() {
  96.             const navToggle = document.querySelector('.nav-toggle');
  97.             const navMenu = document.querySelector('.nav-menu');
  98.             
  99.             navToggle.addEventListener('click', function() {
  100.                 const expanded = this.getAttribute('aria-expanded') === 'true';
  101.                 this.setAttribute('aria-expanded', !expanded);
  102.                 navMenu.classList.toggle('active');
  103.             });
  104.         });
  105.     </script>
  106.    
  107.     <!-- 非关键JavaScript异步加载 -->
  108.     <script src="non-critical.js" async></script>
  109.    
  110.     <!-- Service Worker注册 -->
  111.     <script>
  112.         if ('serviceWorker' in navigator) {
  113.             window.addEventListener('load', function() {
  114.                 navigator.serviceWorker.register('/service-worker.js');
  115.             });
  116.         }
  117.     </script>
  118. </body>
  119. </html>
复制代码

CSS最佳实践
  1. /* CSS最佳实践 */
  2. /* 使用BEM命名约定 */
  3. /* 块(Block) */
  4. .card {
  5.     background-color: #fff;
  6.     border-radius: 4px;
  7.     box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  8.     padding: 20px;
  9. }
  10. /* 元素(Element) */
  11. .card__title {
  12.     font-size: 1.5rem;
  13.     margin-top: 0;
  14.     margin-bottom: 1rem;
  15. }
  16. .card__content {
  17.     font-size: 1rem;
  18.     line-height: 1.6;
  19. }
  20. .card__image {
  21.     width: 100%;
  22.     height: auto;
  23.     border-radius: 4px 4px 0 0;
  24. }
  25. /* 修饰符(Modifier) */
  26. .card--highlighted {
  27.     border: 2px solid #3498db;
  28. }
  29. .card--large {
  30.     padding: 30px;
  31. }
  32. .card__title--small {
  33.     font-size: 1.2rem;
  34. }
  35. /* 使用CSS变量 */
  36. :root {
  37.     --color-primary: #3498db;
  38.     --color-secondary: #2ecc71;
  39.     --color-text: #333;
  40.     --color-background: #fff;
  41.     --color-border: #ddd;
  42.     --spacing-unit: 8px;
  43.     --border-radius: 4px;
  44.     --transition-speed: 0.3s;
  45. }
  46. .button {
  47.     background-color: var(--color-primary);
  48.     color: var(--color-background);
  49.     padding: calc(var(--spacing-unit) * 2) calc(var(--spacing-unit) * 3);
  50.     border-radius: var(--border-radius);
  51.     transition: all var(--transition-speed) ease;
  52. }
  53. .button:hover {
  54.     background-color: #2980b9;
  55. }
  56. /* 使用CSS预处理器(如Sass)*/
  57. /* _variables.scss */
  58. $color-primary: #3498db;
  59. $color-secondary: #2ecc71;
  60. $color-text: #333;
  61. $color-background: #fff;
  62. $color-border: #ddd;
  63. $spacing-unit: 8px;
  64. $border-radius: 4px;
  65. $transition-speed: 0.3s;
  66. /* _mixins.scss */
  67. @mixin button-styles($bg-color, $text-color) {
  68.     background-color: $bg-color;
  69.     color: $text-color;
  70.     padding: $spacing-unit * 2 $spacing-unit * 3;
  71.     border-radius: $border-radius;
  72.     transition: all $transition-speed ease;
  73.    
  74.     &:hover {
  75.         background-color: darken($bg-color, 10%);
  76.     }
  77. }
  78. /* main.scss */
  79. .button {
  80.     @include button-styles($color-primary, $color-background);
  81. }
  82. .button-secondary {
  83.     @include button-styles($color-secondary, $color-background);
  84. }
  85. /* 使用CSS模块(如CSS Modules或CSS-in-JS)*/
  86. /* Button.module.css */
  87. .button {
  88.     background-color: #3498db;
  89.     color: white;
  90.     padding: 10px 20px;
  91.     border-radius: 4px;
  92.     border: none;
  93.     cursor: pointer;
  94.     transition: background-color 0.3s ease;
  95. }
  96. .button:hover {
  97.     background-color: #2980b9;
  98. }
  99. /* 使用CSS框架(如Bootstrap、Tailwind CSS)*/
  100. /* Bootstrap示例 */
  101. <button class="btn btn-primary">主要按钮</button>
  102. /* Tailwind CSS示例 */
  103. <button class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded">
  104.     蓝色按钮
  105. </button>
  106. /* 响应式设计最佳实践 */
  107. /* 移动优先 */
  108. .container {
  109.     width: 100%;
  110.     padding: 15px;
  111. }
  112. @media (min-width: 768px) {
  113.     .container {
  114.         max-width: 750px;
  115.         margin: 0 auto;
  116.     }
  117. }
  118. @media (min-width: 992px) {
  119.     .container {
  120.         max-width: 970px;
  121.     }
  122. }
  123. @media (min-width: 1200px) {
  124.     .container {
  125.         max-width: 1170px;
  126.     }
  127. }
  128. /* 使用相对单位 */
  129. .text {
  130.     font-size: 1rem; /* 相对于根元素字体大小 */
  131.     line-height: 1.5; /* 相对于元素字体大小 */
  132.     margin-bottom: 1em; /* 相对于元素字体大小 */
  133.     padding: 0.5em 1em; /* 相对于元素字体大小 */
  134. }
  135. /* 使用现代布局技术 */
  136. .flex-container {
  137.     display: flex;
  138.     flex-wrap: wrap;
  139.     gap: 20px;
  140. }
  141. .grid-container {
  142.     display: grid;
  143.     grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  144.     gap: 20px;
  145. }
复制代码

JavaScript最佳实践
  1. // JavaScript最佳实践
  2. // 使用ES6+语法
  3. // 使用let和const代替var
  4. const PI = 3.14159;
  5. let radius = 5;
  6. // 使用箭头函数
  7. const circleArea = (radius) => PI * radius * radius;
  8. // 使用模板字符串
  9. const message = `半径为 ${radius} 的圆的面积是 ${circleArea(radius)}`;
  10. // 使用解构赋值
  11. const person = { name: 'John', age: 30, city: 'New York' };
  12. const { name, age } = person;
  13. // 使用数组和对象扩展运算符
  14. const numbers = [1, 2, 3];
  15. const newNumbers = [...numbers, 4, 5];
  16. const personInfo = { ...person, country: 'USA' };
  17. // 使用类
  18. class Person {
  19.     constructor(name, age) {
  20.         this.name = name;
  21.         this.age = age;
  22.     }
  23.    
  24.     greet() {
  25.         return `Hello, my name is ${this.name} and I am ${this.age} years old.`;
  26.     }
  27. }
  28. const john = new Person('John', 30);
  29. console.log(john.greet());
  30. // 使用模块
  31. // math.js
  32. export const add = (a, b) => a + b;
  33. export const subtract = (a, b) => a - b;
  34. export default class Calculator {
  35.     constructor() {
  36.         this.result = 0;
  37.     }
  38.    
  39.     add(num) {
  40.         this.result += num;
  41.         return this;
  42.     }
  43.    
  44.     subtract(num) {
  45.         this.result -= num;
  46.         return this;
  47.     }
  48.    
  49.     getResult() {
  50.         return this.result;
  51.     }
  52. }
  53. // main.js
  54. import Calculator, { add, subtract } from './math.js';
  55. const calc = new Calculator();
  56. const result = calc.add(5).subtract(3).getResult();
  57. console.log(result); // 2
  58. console.log(add(10, 5)); // 15
  59. console.log(subtract(10, 5)); // 5
  60. // 使用异步编程
  61. // 使用Promise
  62. function fetchData(url) {
  63.     return new Promise((resolve, reject) => {
  64.         fetch(url)
  65.             .then(response => {
  66.                 if (response.ok) {
  67.                     return response.json();
  68.                 } else {
  69.                     throw new Error('Network response was not ok');
  70.                 }
  71.             })
  72.             .then(data => resolve(data))
  73.             .catch(error => reject(error));
  74.     });
  75. }
  76. fetchData('https://api.example.com/data')
  77.     .then(data => console.log(data))
  78.     .catch(error => console.error('Error:', error));
  79. // 使用async/await
  80. async function getData() {
  81.     try {
  82.         const response = await fetch('https://api.example.com/data');
  83.         
  84.         if (!response.ok) {
  85.             throw new Error('Network response was not ok');
  86.         }
  87.         
  88.         const data = await response.json();
  89.         console.log(data);
  90.     } catch (error) {
  91.         console.error('Error:', error);
  92.     }
  93. }
  94. getData();
  95. // 使用错误处理
  96. function divide(a, b) {
  97.     if (b === 0) {
  98.         throw new Error('Division by zero');
  99.     }
  100.     return a / b;
  101. }
  102. try {
  103.     const result = divide(10, 0);
  104.     console.log(result);
  105. } catch (error) {
  106.     console.error('Error:', error.message);
  107. } finally {
  108.     console.log('Division operation completed');
  109. }
  110. // 使用函数式编程
  111. // 使用纯函数
  112. const multiply = (a, b) => a * b;
  113. // 使用高阶函数
  114. const numbers = [1, 2, 3, 4, 5];
  115. const doubled = numbers.map(num => num * 2);
  116. const evens = numbers.filter(num => num % 2 === 0);
  117. const sum = numbers.reduce((acc, num) => acc + num, 0);
  118. // 使用组合
  119. const addFive = num => num + 5;
  120. const multiplyByThree = num => num * 3;
  121. const compose = (...fns) => x => fns.reduceRight((v, f) => f(v), x);
  122. const addFiveAndMultiplyByThree = compose(multiplyByThree, addFive);
  123. console.log(addFiveAndMultiplyByThree(10)); // 45
  124. // 使用设计模式
  125. // 单例模式
  126. class Singleton {
  127.     constructor() {
  128.         if (!Singleton.instance) {
  129.             this.data = 'Singleton data';
  130.             Singleton.instance = this;
  131.         }
  132.         return Singleton.instance;
  133.     }
  134. }
  135. const instance1 = new Singleton();
  136. const instance2 = new Singleton();
  137. console.log(instance1 === instance2); // true
  138. // 观察者模式
  139. class Subject {
  140.     constructor() {
  141.         this.observers = [];
  142.     }
  143.    
  144.     subscribe(observer) {
  145.         this.observers.push(observer);
  146.     }
  147.    
  148.     unsubscribe(observer) {
  149.         this.observers = this.observers.filter(obs => obs !== observer);
  150.     }
  151.    
  152.     notify(data) {
  153.         this.observers.forEach(observer => observer.update(data));
  154.     }
  155. }
  156. class Observer {
  157.     update(data) {
  158.         console.log('Received data:', data);
  159.     }
  160. }
  161. const subject = new Subject();
  162. const observer1 = new Observer();
  163. const observer2 = new Observer();
  164. subject.subscribe(observer1);
  165. subject.subscribe(observer2);
  166. subject.notify('Hello Observers!');
  167. // 使用性能优化技术
  168. // 使用防抖和节流
  169. function debounce(func, wait) {
  170.     let timeout;
  171.     return function() {
  172.         const context = this;
  173.         const args = arguments;
  174.         clearTimeout(timeout);
  175.         timeout = setTimeout(() => func.apply(context, args), wait);
  176.     };
  177. }
  178. function throttle(func, limit) {
  179.     let inThrottle;
  180.     return function() {
  181.         const args = arguments;
  182.         const context = this;
  183.         if (!inThrottle) {
  184.             func.apply(context, args);
  185.             inThrottle = true;
  186.             setTimeout(() => inThrottle = false, limit);
  187.         }
  188.     };
  189. }
  190. // 使用requestAnimationFrame
  191. function animate() {
  192.     // 动画逻辑
  193.     requestAnimationFrame(animate);
  194. }
  195. requestAnimationFrame(animate);
  196. // 使用Web Workers处理密集计算
  197. // main.js
  198. const worker = new Worker('worker.js');
  199. worker.postMessage({ command: 'calculate', data: [1, 2, 3, 4, 5] });
  200. worker.onmessage = function(event) {
  201.     console.log('Result:', event.data.result);
  202. };
  203. // worker.js
  204. self.onmessage = function(event) {
  205.     if (event.data.command === 'calculate') {
  206.         const result = event.data.data.reduce((sum, num) => sum + num, 0);
  207.         self.postMessage({ result: result });
  208.     }
  209. };
复制代码

可访问性最佳实践
  1. <!-- 可访问性最佳实践 -->
  2. <!-- 使用语义化HTML -->
  3. <nav aria-label="主导航">
  4.     <ul>
  5.         <li><a href="/">首页</a></li>
  6.         <li><a href="/about">关于</a></li>
  7.         <li><a href="/services">服务</a></li>
  8.         <li><a href="/contact">联系</a></li>
  9.     </ul>
  10. </nav>
  11. <main>
  12.     <section aria-labelledby="section1-heading">
  13.         <h2 id="section1-heading">章节标题</h2>
  14.         <p>章节内容...</p>
  15.     </section>
  16. </main>
  17. <!-- 提供替代文本 -->
  18. <img src="photo.jpg" alt="描述照片内容">
  19. <!-- 对于装饰性图片,使用空alt属性 -->
  20. <img src="decorative-image.jpg" alt="">
  21. <!-- 使用ARIA属性 -->
  22. <button aria-expanded="false" aria-controls="menu">菜单</button>
  23. <div id="menu" aria-hidden="true">
  24.     <!-- 菜单内容 -->
  25. </div>
  26. <!-- 提供跳过导航链接 -->
  27. <a href="#main-content" class="skip-link">跳转到主要内容</a>
  28. <!-- 确保表单可访问 -->
  29. <form>
  30.     <div>
  31.         <label for="name">姓名:</label>
  32.         <input type="text" id="name" name="name" required aria-required="true">
  33.     </div>
  34.    
  35.     <div>
  36.         <label for="email">电子邮件:</label>
  37.         <input type="email" id="email" name="email" required aria-required="true">
  38.         <span id="email-error" class="error-message" aria-live="polite"></span>
  39.     </div>
  40.    
  41.     <div>
  42.         <fieldset>
  43.             <legend>性别:</legend>
  44.             <input type="radio" id="male" name="gender" value="male">
  45.             <label for="male">男</label>
  46.             
  47.             <input type="radio" id="female" name="gender" value="female">
  48.             <label for="female">女</label>
  49.             
  50.             <input type="radio" id="other" name="gender" value="other">
  51.             <label for="other">其他</label>
  52.         </fieldset>
  53.     </div>
  54.    
  55.     <button type="submit">提交</button>
  56. </form>
  57. <!-- 确保颜色对比度 -->
  58. <style>
  59.     /* 良好的颜色对比度 */
  60.     .text {
  61.         color: #333; /* 深色文本 */
  62.         background-color: #fff; /* 浅色背景 */
  63.     }
  64.    
  65.     /* 避免仅使用颜色传达信息 */
  66.     .error {
  67.         color: #d32f2f;
  68.         font-weight: bold;
  69.         text-decoration: underline; /* 额外的视觉提示 */
  70.     }
  71.    
  72.     /* 确保链接可识别 */
  73.     a {
  74.         color: #1976d2;
  75.         text-decoration: underline;
  76.     }
  77.    
  78.     a:hover, a:focus {
  79.         color: #0d47a1;
  80.         text-decoration: underline;
  81.     }
  82.    
  83.     /* 确保焦点可见 */
  84.     button:focus, a:focus, input:focus, textarea:focus, select:focus {
  85.         outline: 2px solid #1976d2;
  86.         outline-offset: 2px;
  87.     }
  88. </style>
  89. <!-- 提供键盘导航支持 -->
  90. <div role="tablist" aria-label="选项卡">
  91.     <button role="tab" aria-selected="true" aria-controls="panel1" id="tab1">选项卡1</button>
  92.     <button role="tab" aria-selected="false" aria-controls="panel2" id="tab2">选项卡2</button>
  93.     <button role="tab" aria-selected="false" aria-controls="panel3" id="tab3">选项卡3</button>
  94. </div>
  95. <div role="tabpanel" id="panel1" aria-labelledby="tab1">
  96.     <p>选项卡1内容</p>
  97. </div>
  98. <div role="tabpanel" id="panel2" aria-labelledby="tab2" hidden>
  99.     <p>选项卡2内容</p>
  100. </div>
  101. <div role="tabpanel" id="panel3" aria-labelledby="tab3" hidden>
  102.     <p>选项卡3内容</p>
  103. </div>
  104. <script>
  105.     // 选项卡键盘导航
  106.     const tabs = document.querySelectorAll('[role="tab"]');
  107.     const tabList = document.querySelector('[role="tablist"]');
  108.    
  109.     // 为选项卡列表添加方向键导航
  110.     tabList.addEventListener('keydown', (e) => {
  111.         const key = e.key;
  112.         let currentTab = document.activeElement;
  113.         
  114.         if (key === 'ArrowRight' || key === 'ArrowLeft') {
  115.             if (key === 'ArrowRight') {
  116.                 // 移动到下一个选项卡
  117.                 if (currentTab.nextElementSibling) {
  118.                     currentTab.nextElementSibling.focus();
  119.                 } else {
  120.                     tabs[0].focus();
  121.                 }
  122.             } else if (key === 'ArrowLeft') {
  123.                 // 移动到上一个选项卡
  124.                 if (currentTab.previousElementSibling) {
  125.                     currentTab.previousElementSibling.focus();
  126.                 } else {
  127.                     tabs[tabs.length - 1].focus();
  128.                 }
  129.             }
  130.             
  131.             // 激活当前选项卡
  132.             currentTab.click();
  133.             e.preventDefault();
  134.         }
  135.     });
  136.    
  137.     // 选项卡点击事件
  138.     tabs.forEach(tab => {
  139.         tab.addEventListener('click', () => {
  140.             // 取消所有选项卡的选中状态
  141.             tabs.forEach(t => {
  142.                 t.setAttribute('aria-selected', 'false');
  143.             });
  144.             
  145.             // 隐藏所有面板
  146.             document.querySelectorAll('[role="tabpanel"]').forEach(panel => {
  147.                 panel.setAttribute('hidden', '');
  148.             });
  149.             
  150.             // 激活当前选项卡
  151.             tab.setAttribute('aria-selected', 'true');
  152.             
  153.             // 显示对应面板
  154.             const panelId = tab.getAttribute('aria-controls');
  155.             document.getElementById(panelId).removeAttribute('hidden');
  156.         });
  157.     });
  158. </script>
  159. <!-- 提供字幕和转录 -->
  160. <video controls>
  161.     <source src="video.mp4" type="video/mp4">
  162.     <track kind="captions" src="captions.vtt" srclang="zh" label="中文字幕">
  163.     您的浏览器不支持视频标签。
  164. </video>
  165. <!-- 提供视频转录 -->
  166. <div class="transcript">
  167.     <h3>视频转录</h3>
  168.     <p>这里是视频内容的文字转录...</p>
  169. </div>
  170. <!-- 确保响应式设计适应不同设备 -->
  171. <style>
  172.     /* 基本样式 */
  173.     .container {
  174.         width: 100%;
  175.         max-width: 1200px;
  176.         margin: 0 auto;
  177.         padding: 20px;
  178.     }
  179.    
  180.     /* 响应式字体大小 */
  181.     html {
  182.         font-size: 16px;
  183.     }
  184.    
  185.     @media (max-width: 768px) {
  186.         html {
  187.             font-size: 14px;
  188.         }
  189.     }
  190.    
  191.     @media (max-width: 480px) {
  192.         html {
  193.             font-size: 12px;
  194.         }
  195.     }
  196.    
  197.     /* 响应式导航 */
  198.     .nav-menu {
  199.         display: flex;
  200.         flex-direction: row;
  201.     }
  202.    
  203.     @media (max-width: 768px) {
  204.         .nav-menu {
  205.             flex-direction: column;
  206.         }
  207.     }
  208.    
  209.     /* 响应式表格 */
  210.     .responsive-table {
  211.         width: 100%;
  212.         overflow-x: auto;
  213.     }
  214.    
  215.     table {
  216.         width: 100%;
  217.         min-width: 600px;
  218.     }
  219.    
  220.     /* 响应式图片 */
  221.     img {
  222.         max-width: 100%;
  223.         height: auto;
  224.     }
  225. </style>
复制代码

实战项目:构建响应式网站

让我们通过一个实际项目来应用我们学到的所有知识。我们将构建一个响应式的个人作品集网站,包含首页、关于页面、作品展示页面和联系页面。

项目结构
  1. portfolio-website/
  2. ├── index.html
  3. ├── about.html
  4. ├── portfolio.html
  5. ├── contact.html
  6. ├── css/
  7. │   ├── normalize.css
  8. │   ├── style.css
  9. │   └── responsive.css
  10. ├── js/
  11. │   ├── main.js
  12. │   └── contact.js
  13. ├── images/
  14. │   ├── logo.svg
  15. │   ├── hero-bg.jpg
  16. │   ├── profile.jpg
  17. │   └── projects/
  18. │       ├── project1.jpg
  19. │       ├── project2.jpg
  20. │       └── project3.jpg
  21. └── fonts/
  22.     └── roboto/
  23.         ├── Roboto-Regular.ttf
  24.         ├── Roboto-Bold.ttf
  25.         └── Roboto-Italic.ttf
复制代码

首页 (index.html)
  1. <!DOCTYPE html>
  2. <html lang="zh-CN">
  3. <head>
  4.     <meta charset="UTF-8">
  5.     <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6.     <meta name="description" content="个人作品集网站,展示我的项目和技能">
  7.     <meta name="keywords" content="作品集, 网页开发, 设计">
  8.     <title>张三 - 个人作品集</title>
  9.    
  10.     <!-- 预加载关键资源 -->
  11.     <link rel="preload" href="css/normalize.css" as="style">
  12.     <link rel="preload" href="css/style.css" as="style">
  13.     <link rel="preload" href="images/logo.svg" as="image">
  14.    
  15.     <!-- CSS -->
  16.     <link rel="stylesheet" href="css/normalize.css">
  17.     <link rel="stylesheet" href="css/style.css">
  18.    
  19.     <!-- 字体 -->
  20.     <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap" rel="stylesheet">
  21.    
  22.     <!-- 图标 -->
  23.     <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
  24. </head>
  25. <body>
  26.     <!-- 跳转到主要内容链接 -->
  27.     <a href="#main-content" class="skip-link">跳转到主要内容</a>
  28.    
  29.     <!-- 页面头部 -->
  30.     <header class="header">
  31.         <div class="container">
  32.             <div class="logo">
  33.                 <a href="index.html">
  34.                     <img src="images/logo.svg" alt="张三个人标志">
  35.                 </a>
  36.             </div>
  37.             
  38.             <nav class="main-nav" aria-label="主导航">
  39.                 <button class="nav-toggle" aria-expanded="false" aria-controls="nav-menu">
  40.                     <span class="sr-only">菜单</span>
  41.                     <span class="icon-bar"></span>
  42.                     <span class="icon-bar"></span>
  43.                     <span class="icon-bar"></span>
  44.                 </button>
  45.                
  46.                 <ul id="nav-menu" class="nav-menu">
  47.                     <li><a href="index.html" class="active">首页</a></li>
  48.                     <li><a href="about.html">关于我</a></li>
  49.                     <li><a href="portfolio.html">作品集</a></li>
  50.                     <li><a href="contact.html">联系我</a></li>
  51.                 </ul>
  52.             </nav>
  53.         </div>
  54.     </header>
  55.    
  56.     <!-- 主要内容 -->
  57.     <main id="main-content">
  58.         <!-- 英雄区域 -->
  59.         <section class="hero">
  60.             <div class="hero-bg">
  61.                 <img src="images/hero-bg.jpg" alt="背景图片">
  62.             </div>
  63.             <div class="hero-content">
  64.                 <div class="container">
  65.                     <h1>你好,我是张三</h1>
  66.                     <p>前端开发工程师 & UI设计师</p>
  67.                     <a href="portfolio.html" class="btn btn-primary">查看我的作品</a>
  68.                 </div>
  69.             </div>
  70.         </section>
  71.         
  72.         <!-- 服务区域 -->
  73.         <section class="services">
  74.             <div class="container">
  75.                 <h2>我的服务</h2>
  76.                 <div class="services-grid">
  77.                     <div class="service-card">
  78.                         <div class="service-icon">
  79.                             <i class="fas fa-code"></i>
  80.                         </div>
  81.                         <h3>网页开发</h3>
  82.                         <p>使用最新的HTML5、CSS3和JavaScript技术,创建响应式、高性能的网站。</p>
  83.                     </div>
  84.                     
  85.                     <div class="service-card">
  86.                         <div class="service-icon">
  87.                             <i class="fas fa-paint-brush"></i>
  88.                         </div>
  89.                         <h3>UI设计</h3>
  90.                         <p>设计美观、直观的用户界面,提供出色的用户体验。</p>
  91.                     </div>
  92.                     
  93.                     <div class="service-card">
  94.                         <div class="service-icon">
  95.                             <i class="fas fa-mobile-alt"></i>
  96.                         </div>
  97.                         <h3>响应式设计</h3>
  98.                         <p>确保网站在各种设备上都能完美显示,从桌面到移动设备。</p>
  99.                     </div>
  100.                 </div>
  101.             </div>
  102.         </section>
  103.         
  104.         <!-- 最新作品 -->
  105.         <section class="recent-projects">
  106.             <div class="container">
  107.                 <h2>最新作品</h2>
  108.                 <div class="projects-grid">
  109.                     <article class="project-card">
  110.                         <div class="project-image">
  111.                             <img src="images/projects/project1.jpg" alt="电子商务网站">
  112.                             <div class="project-overlay">
  113.                                 <a href="portfolio.html#project1" class="btn btn-light">查看详情</a>
  114.                             </div>
  115.                         </div>
  116.                         <div class="project-info">
  117.                             <h3>电子商务网站</h3>
  118.                             <p>一个功能齐全的电子商务平台,具有购物车和支付功能。</p>
  119.                         </div>
  120.                     </article>
  121.                     
  122.                     <article class="project-card">
  123.                         <div class="project-image">
  124.                             <img src="images/projects/project2.jpg" alt="社交媒体应用">
  125.                             <div class="project-overlay">
  126.                                 <a href="portfolio.html#project2" class="btn btn-light">查看详情</a>
  127.                             </div>
  128.                         </div>
  129.                         <div class="project-info">
  130.                             <h3>社交媒体应用</h3>
  131.                             <p>一个现代化的社交媒体应用,具有实时聊天和内容分享功能。</p>
  132.                         </div>
  133.                     </article>
  134.                     
  135.                     <article class="project-card">
  136.                         <div class="project-image">
  137.                             <img src="images/projects/project3.jpg" alt="企业网站">
  138.                             <div class="project-overlay">
  139.                                 <a href="portfolio.html#project3" class="btn btn-light">查看详情</a>
  140.                             </div>
  141.                         </div>
  142.                         <div class="project-info">
  143.                             <h3>企业网站</h3>
  144.                             <p>为一家科技公司设计的现代化企业网站,具有动画效果和交互功能。</p>
  145.                         </div>
  146.                     </article>
  147.                 </div>
  148.                
  149.                 <div class="text-center">
  150.                     <a href="portfolio.html" class="btn btn-secondary">查看所有作品</a>
  151.                 </div>
  152.             </div>
  153.         </section>
  154.         
  155.         <!-- 客户评价 -->
  156.         <section class="testimonials">
  157.             <div class="container">
  158.                 <h2>客户评价</h2>
  159.                 <div class="testimonials-slider">
  160.                     <div class="testimonial-card active">
  161.                         <div class="testimonial-content">
  162.                             <p>"张三是一位出色的开发者和设计师。他不仅技术精湛,而且非常注重细节,能够准确理解并实现客户的需求。"</p>
  163.                         </div>
  164.                         <div class="testimonial-author">
  165.                             <img src="https://io.pixtech.org/pixtech/forum/202509/17/8ce030a518824fd5.webp" alt="李四头像">
  166.                             <div>
  167.                                 <h4>李四</h4>
  168.                                 <p>ABC公司CEO</p>
  169.                             </div>
  170.                         </div>
  171.                     </div>
  172.                     
  173.                     <div class="testimonial-card">
  174.                         <div class="testimonial-content">
  175.                             <p>"与张三合作是一次非常愉快的经历。他专业、高效,并且总是能够按时交付高质量的工作。"</p>
  176.                         </div>
  177.                         <div class="testimonial-author">
  178.                             <img src="https://io.pixtech.org/pixtech/forum/202509/17/cf198110774e4b66.webp" alt="王五头像">
  179.                             <div>
  180.                                 <h4>王五</h4>
  181.                                 <p>XYZ设计总监</p>
  182.                             </div>
  183.                         </div>
  184.                     </div>
  185.                     
  186.                     <div class="testimonial-card">
  187.                         <div class="testimonial-content">
  188.                             <p>"张三的网站设计不仅美观,而且功能强大。我们的网站上线后,用户参与度显著提高。"</p>
  189.                         </div>
  190.                         <div class="testimonial-author">
  191.                             <img src="https://io.pixtech.org/pixtech/forum/202509/17/9bcc4dbd6ea44c32.webp" alt="赵六头像">
  192.                             <div>
  193.                                 <h4>赵六</h4>
  194.                                 <p>DEF公司市场经理</p>
  195.                             </div>
  196.                         </div>
  197.                     </div>
  198.                 </div>
  199.                
  200.                 <div class="slider-controls">
  201.                     <button class="slider-control prev" aria-label="上一个评价">
  202.                         <i class="fas fa-chevron-left"></i>
  203.                     </button>
  204.                     <button class="slider-control next" aria-label="下一个评价">
  205.                         <i class="fas fa-chevron-right"></i>
  206.                     </button>
  207.                 </div>
  208.             </div>
  209.         </section>
  210.         
  211.         <!-- 联系区域 -->
  212.         <section class="contact-cta">
  213.             <div class="container">
  214.                 <h2>有项目想法?让我们一起实现它!</h2>
  215.                 <p>如果您有任何问题或项目需求,请随时与我联系。</p>
  216.                 <a href="contact.html" class="btn btn-primary">联系我</a>
  217.             </div>
  218.         </section>
  219.     </main>
  220.    
  221.     <!-- 页面底部 -->
  222.     <footer class="footer">
  223.         <div class="container">
  224.             <div class="footer-content">
  225.                 <div class="footer-about">
  226.                     <h3>关于我</h3>
  227.                     <p>我是一名前端开发工程师和UI设计师,专注于创建美观、功能强大的网站和应用程序。</p>
  228.                     <div class="social-links">
  229.                         <a href="https://github.com" target="_blank" aria-label="GitHub">
  230.                             <i class="fab fa-github"></i>
  231.                         </a>
  232.                         <a href="https://linkedin.com" target="_blank" aria-label="LinkedIn">
  233.                             <i class="fab fa-linkedin"></i>
  234.                         </a>
  235.                         <a href="https://twitter.com" target="_blank" aria-label="Twitter">
  236.                             <i class="fab fa-twitter"></i>
  237.                         </a>
  238.                         <a href="https://dribbble.com" target="_blank" aria-label="Dribbble">
  239.                             <i class="fab fa-dribbble"></i>
  240.                         </a>
  241.                     </div>
  242.                 </div>
  243.                
  244.                 <div class="footer-links">
  245.                     <h3>快速链接</h3>
  246.                     <ul>
  247.                         <li><a href="index.html">首页</a></li>
  248.                         <li><a href="about.html">关于我</a></li>
  249.                         <li><a href="portfolio.html">作品集</a></li>
  250.                         <li><a href="contact.html">联系我</a></li>
  251.                     </ul>
  252.                 </div>
  253.                
  254.                 <div class="footer-contact">
  255.                     <h3>联系信息</h3>
  256.                     <ul>
  257.                         <li>
  258.                             <i class="fas fa-envelope"></i>
  259.                             <a href="mailto:zhangsan@example.com">zhangsan@example.com</a>
  260.                         </li>
  261.                         <li>
  262.                             <i class="fas fa-phone"></i>
  263.                             <a href="tel:+8613800138000">+86 138 0013 8000</a>
  264.                         </li>
  265.                         <li>
  266.                             <i class="fas fa-map-marker-alt"></i>
  267.                             <span>北京市朝阳区某某街道123号</span>
  268.                         </li>
  269.                     </ul>
  270.                 </div>
  271.             </div>
  272.             
  273.             <div class="footer-bottom">
  274.                 <p>&copy; 2023 张三. 保留所有权利.</p>
  275.             </div>
  276.         </div>
  277.     </footer>
  278.    
  279.     <!-- JavaScript -->
  280.     <script src="js/main.js"></script>
  281. </body>
  282. </html>
复制代码

主样式表 (css/style.css)
  1. /* CSS变量 */
  2. :root {
  3.     --color-primary: #3498db;
  4.     --color-secondary: #2ecc71;
  5.     --color-accent: #e74c3c;
  6.     --color-dark: #2c3e50;
  7.     --color-light: #ecf0f1;
  8.     --color-text: #333;
  9.     --color-text-light: #777;
  10.     --color-white: #fff;
  11.     --color-black: #000;
  12.     --color-gray: #95a5a6;
  13.     --color-border: #ddd;
  14.    
  15.     --spacing-unit: 8px;
  16.     --border-radius: 4px;
  17.     --box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
  18.     --transition-speed: 0.3s;
  19.    
  20.     --font-primary: 'Roboto', sans-serif;
  21.     --font-size-base: 16px;
  22.     --line-height-base: 1.6;
  23. }
  24. /* 基础样式 */
  25. * {
  26.     margin: 0;
  27.     padding: 0;
  28.     box-sizing: border-box;
  29. }
  30. html {
  31.     font-size: var(--font-size-base);
  32.     scroll-behavior: smooth;
  33. }
  34. body {
  35.     font-family: var(--font-primary);
  36.     line-height: var(--line-height-base);
  37.     color: var(--color-text);
  38.     background-color: var(--color-white);
  39. }
  40. .container {
  41.     width: 100%;
  42.     max-width: 1200px;
  43.     margin: 0 auto;
  44.     padding: 0 var(--spacing-unit * 2);
  45. }
  46. /* 跳过链接 */
  47. .skip-link {
  48.     position: absolute;
  49.     top: -40px;
  50.     left: 0;
  51.     background: var(--color-primary);
  52.     color: var(--color-white);
  53.     padding: var(--spacing-unit);
  54.     text-decoration: none;
  55.     border-radius: 0 0 var(--border-radius) 0;
  56.     z-index: 100;
  57. }
  58. .skip-link:focus {
  59.     top: 0;
  60. }
  61. /* 头部样式 */
  62. .header {
  63.     background-color: var(--color-white);
  64.     box-shadow: var(--box-shadow);
  65.     position: sticky;
  66.     top: 0;
  67.     z-index: 1000;
  68. }
  69. .header .container {
  70.     display: flex;
  71.     justify-content: space-between;
  72.     align-items: center;
  73.     padding: var(--spacing-unit * 2);
  74. }
  75. .logo img {
  76.     height: 40px;
  77.     width: auto;
  78. }
  79. /* 导航样式 */
  80. .main-nav {
  81.     position: relative;
  82. }
  83. .nav-toggle {
  84.     display: none;
  85.     background: none;
  86.     border: none;
  87.     cursor: pointer;
  88.     padding: var(--spacing-unit);
  89. }
  90. .nav-toggle .icon-bar {
  91.     display: block;
  92.     width: 25px;
  93.     height: 3px;
  94.     background-color: var(--color-dark);
  95.     margin: 5px 0;
  96.     transition: all var(--transition-speed) ease;
  97. }
  98. .nav-menu {
  99.     display: flex;
  100.     list-style: none;
  101. }
  102. .nav-menu li {
  103.     margin-left: var(--spacing-unit * 3);
  104. }
  105. .nav-menu a {
  106.     text-decoration: none;
  107.     color: var(--color-dark);
  108.     font-weight: 500;
  109.     position: relative;
  110.     transition: color var(--transition-speed) ease;
  111. }
  112. .nav-menu a::after {
  113.     content: '';
  114.     position: absolute;
  115.     bottom: -5px;
  116.     left: 0;
  117.     width: 0;
  118.     height: 2px;
  119.     background-color: var(--color-primary);
  120.     transition: width var(--transition-speed) ease;
  121. }
  122. .nav-menu a:hover,
  123. .nav-menu a.active {
  124.     color: var(--color-primary);
  125. }
  126. .nav-menu a:hover::after,
  127. .nav-menu a.active::after {
  128.     width: 100%;
  129. }
  130. /* 按钮样式 */
  131. .btn {
  132.     display: inline-block;
  133.     padding: var(--spacing-unit * 1.5) var(--spacing-unit * 3);
  134.     background-color: var(--color-primary);
  135.     color: var(--color-white);
  136.     text-decoration: none;
  137.     border-radius: var(--border-radius);
  138.     border: none;
  139.     cursor: pointer;
  140.     font-weight: 500;
  141.     text-align: center;
  142.     transition: all var(--transition-speed) ease;
  143. }
  144. .btn:hover {
  145.     background-color: #2980b9;
  146.     transform: translateY(-2px);
  147.     box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
  148. }
  149. .btn:focus {
  150.     outline: 2px solid var(--color-primary);
  151.     outline-offset: 2px;
  152. }
  153. .btn-secondary {
  154.     background-color: var(--color-secondary);
  155. }
  156. .btn-secondary:hover {
  157.     background-color: #27ae60;
  158. }
  159. .btn-light {
  160.     background-color: var(--color-white);
  161.     color: var(--color-dark);
  162.     border: 1px solid var(--color-border);
  163. }
  164. .btn-light:hover {
  165.     background-color: var(--color-light);
  166. }
  167. /* 英雄区域样式 */
  168. .hero {
  169.     position: relative;
  170.     height: 500px;
  171.     overflow: hidden;
  172. }
  173. .hero-bg {
  174.     position: absolute;
  175.     top: 0;
  176.     left: 0;
  177.     width: 100%;
  178.     height: 100%;
  179.     z-index: -1;
  180. }
  181. .hero-bg img {
  182.     width: 100%;
  183.     height: 100%;
  184.     object-fit: cover;
  185. }
  186. .hero-bg::after {
  187.     content: '';
  188.     position: absolute;
  189.     top: 0;
  190.     left: 0;
  191.     width: 100%;
  192.     height: 100%;
  193.     background: linear-gradient(rgba(0, 0, 0, 0.5), rgba(0, 0, 0, 0.7));
  194. }
  195. .hero-content {
  196.     position: absolute;
  197.     top: 50%;
  198.     left: 50%;
  199.     transform: translate(-50%, -50%);
  200.     text-align: center;
  201.     color: var(--color-white);
  202.     width: 100%;
  203. }
  204. .hero-content h1 {
  205.     font-size: 3rem;
  206.     margin-bottom: var(--spacing-unit * 2);
  207. }
  208. .hero-content p {
  209.     font-size: 1.5rem;
  210.     margin-bottom: var(--spacing-unit * 3);
  211. }
  212. /* 服务区域样式 */
  213. .services {
  214.     padding: var(--spacing-unit * 10) 0;
  215.     background-color: var(--color-light);
  216. }
  217. .services h2 {
  218.     text-align: center;
  219.     margin-bottom: var(--spacing-unit * 5);
  220.     color: var(--color-dark);
  221. }
  222. .services-grid {
  223.     display: grid;
  224.     grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  225.     gap: var(--spacing-unit * 4);
  226. }
  227. .service-card {
  228.     background-color: var(--color-white);
  229.     border-radius: var(--border-radius);
  230.     padding: var(--spacing-unit * 4);
  231.     text-align: center;
  232.     box-shadow: var(--box-shadow);
  233.     transition: transform var(--transition-speed) ease;
  234. }
  235. .service-card:hover {
  236.     transform: translateY(-10px);
  237. }
  238. .service-icon {
  239.     font-size: 3rem;
  240.     color: var(--color-primary);
  241.     margin-bottom: var(--spacing-unit * 3);
  242. }
  243. .service-card h3 {
  244.     font-size: 1.5rem;
  245.     margin-bottom: var(--spacing-unit * 2);
  246.     color: var(--color-dark);
  247. }
  248. .service-card p {
  249.     color: var(--color-text-light);
  250. }
  251. /* 最新作品样式 */
  252. .recent-projects {
  253.     padding: var(--spacing-unit * 10) 0;
  254. }
  255. .recent-projects h2 {
  256.     text-align: center;
  257.     margin-bottom: var(--spacing-unit * 5);
  258.     color: var(--color-dark);
  259. }
  260. .projects-grid {
  261.     display: grid;
  262.     grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  263.     gap: var(--spacing-unit * 4);
  264.     margin-bottom: var(--spacing-unit * 5);
  265. }
  266. .project-card {
  267.     background-color: var(--color-white);
  268.     border-radius: var(--border-radius);
  269.     overflow: hidden;
  270.     box-shadow: var(--box-shadow);
  271.     transition: transform var(--transition-speed) ease;
  272. }
  273. .project-card:hover {
  274.     transform: translateY(-10px);
  275. }
  276. .project-image {
  277.     position: relative;
  278.     height: 200px;
  279.     overflow: hidden;
  280. }
  281. .project-image img {
  282.     width: 100%;
  283.     height: 100%;
  284.     object-fit: cover;
  285.     transition: transform var(--transition-speed) ease;
  286. }
  287. .project-card:hover .project-image img {
  288.     transform: scale(1.1);
  289. }
  290. .project-overlay {
  291.     position: absolute;
  292.     top: 0;
  293.     left: 0;
  294.     width: 100%;
  295.     height: 100%;
  296.     background: rgba(0, 0, 0, 0.7);
  297.     display: flex;
  298.     justify-content: center;
  299.     align-items: center;
  300.     opacity: 0;
  301.     transition: opacity var(--transition-speed) ease;
  302. }
  303. .project-card:hover .project-overlay {
  304.     opacity: 1;
  305. }
  306. .project-info {
  307.     padding: var(--spacing-unit * 3);
  308. }
  309. .project-info h3 {
  310.     font-size: 1.25rem;
  311.     margin-bottom: var(--spacing-unit * 2);
  312.     color: var(--color-dark);
  313. }
  314. .project-info p {
  315.     color: var(--color-text-light);
  316. }
  317. .text-center {
  318.     text-align: center;
  319. }
  320. /* 客户评价样式 */
  321. .testimonials {
  322.     padding: var(--spacing-unit * 10) 0;
  323.     background-color: var(--color-light);
  324. }
  325. .testimonials h2 {
  326.     text-align: center;
  327.     margin-bottom: var(--spacing-unit * 5);
  328.     color: var(--color-dark);
  329. }
  330. .testimonials-slider {
  331.     position: relative;
  332.     max-width: 800px;
  333.     margin: 0 auto;
  334. }
  335. .testimonial-card {
  336.     background-color: var(--color-white);
  337.     border-radius: var(--border-radius);
  338.     padding: var(--spacing-unit * 4);
  339.     box-shadow: var(--box-shadow);
  340.     position: absolute;
  341.     top: 0;
  342.     left: 0;
  343.     width: 100%;
  344.     opacity: 0;
  345.     transition: opacity var(--transition-speed) ease;
  346. }
  347. .testimonial-card.active {
  348.     position: relative;
  349.     opacity: 1;
  350. }
  351. .testimonial-content p {
  352.     font-style: italic;
  353.     margin-bottom: var(--spacing-unit * 3);
  354.     color: var(--color-text-light);
  355. }
  356. .testimonial-content p::before {
  357.     content: '"';
  358.     font-size: 3rem;
  359.     color: var(--color-primary);
  360.     line-height: 0;
  361.     position: relative;
  362.     top: 15px;
  363. }
  364. .testimonial-author {
  365.     display: flex;
  366.     align-items: center;
  367. }
  368. .testimonial-author img {
  369.     width: 50px;
  370.     height: 50px;
  371.     border-radius: 50%;
  372.     margin-right: var(--spacing-unit * 2);
  373. }
  374. .testimonial-author h4 {
  375.     margin-bottom: 0;
  376.     color: var(--color-dark);
  377. }
  378. .testimonial-author p {
  379.     margin: 0;
  380.     color: var(--color-text-light);
  381.     font-size: 0.9rem;
  382. }
  383. .slider-controls {
  384.     display: flex;
  385.     justify-content: center;
  386.     margin-top: var(--spacing-unit * 5);
  387. }
  388. .slider-control {
  389.     background-color: var(--color-primary);
  390.     color: var(--color-white);
  391.     border: none;
  392.     border-radius: 50%;
  393.     width: 40px;
  394.     height: 40px;
  395.     margin: 0 var(--spacing-unit);
  396.     cursor: pointer;
  397.     transition: background-color var(--transition-speed) ease;
  398. }
  399. .slider-control:hover {
  400.     background-color: #2980b9;
  401. }
  402. .slider-control:focus {
  403.     outline: 2px solid var(--color-primary);
  404.     outline-offset: 2px;
  405. }
  406. /* 联系区域样式 */
  407. .contact-cta {
  408.     padding: var(--spacing-unit * 10) 0;
  409.     background-color: var(--color-primary);
  410.     color: var(--color-white);
  411.     text-align: center;
  412. }
  413. .contact-cta h2 {
  414.     margin-bottom: var(--spacing-unit * 2);
  415. }
  416. .contact-cta p {
  417.     margin-bottom: var(--spacing-unit * 4);
  418.     max-width: 600px;
  419.     margin-left: auto;
  420.     margin-right: auto;
  421. }
  422. .contact-cta .btn {
  423.     background-color: var(--color-white);
  424.     color: var(--color-primary);
  425. }
  426. .contact-cta .btn:hover {
  427.     background-color: var(--color-light);
  428. }
  429. /* 页脚样式 */
  430. .footer {
  431.     background-color: var(--color-dark);
  432.     color: var(--color-white);
  433.     padding: var(--spacing-unit * 8) 0 var(--spacing-unit * 4);
  434. }
  435. .footer-content {
  436.     display: grid;
  437.     grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  438.     gap: var(--spacing-unit * 4);
  439.     margin-bottom: var(--spacing-unit * 6);
  440. }
  441. .footer-about h3,
  442. .footer-links h3,
  443. .footer-contact h3 {
  444.     font-size: 1.25rem;
  445.     margin-bottom: var(--spacing-unit * 3);
  446.     color: var(--color-white);
  447. }
  448. .footer-about p {
  449.     color: var(--color-gray);
  450.     margin-bottom: var(--spacing-unit * 3);
  451. }
  452. .social-links {
  453.     display: flex;
  454.     gap: var(--spacing-unit * 2);
  455. }
  456. .social-links a {
  457.     display: flex;
  458.     justify-content: center;
  459.     align-items: center;
  460.     width: 40px;
  461.     height: 40px;
  462.     background-color: rgba(255, 255, 255, 0.1);
  463.     color: var(--color-white);
  464.     border-radius: 50%;
  465.     transition: background-color var(--transition-speed) ease;
  466. }
  467. .social-links a:hover {
  468.     background-color: var(--color-primary);
  469. }
  470. .footer-links ul {
  471.     list-style: none;
  472. }
  473. .footer-links li {
  474.     margin-bottom: var(--spacing-unit);
  475. }
  476. .footer-links a {
  477.     color: var(--color-gray);
  478.     text-decoration: none;
  479.     transition: color var(--transition-speed) ease;
  480. }
  481. .footer-links a:hover {
  482.     color: var(--color-white);
  483. }
  484. .footer-contact ul {
  485.     list-style: none;
  486. }
  487. .footer-contact li {
  488.     display: flex;
  489.     align-items: flex-start;
  490.     margin-bottom: var(--spacing-unit);
  491. }
  492. .footer-contact i {
  493.     margin-right: var(--spacing-unit * 2);
  494.     margin-top: var(--spacing-unit / 2);
  495.     color: var(--color-primary);
  496. }
  497. .footer-contact a {
  498.     color: var(--color-gray);
  499.     text-decoration: none;
  500.     transition: color var(--transition-speed) ease;
  501. }
  502. .footer-contact a:hover {
  503.     color: var(--color-white);
  504. }
  505. .footer-bottom {
  506.     text-align: center;
  507.     padding-top: var(--spacing-unit * 4);
  508.     border-top: 1px solid rgba(255, 255, 255, 0.1);
  509. }
  510. .footer-bottom p {
  511.     color: var(--color-gray);
  512. }
  513. /* 辅助类 */
  514. .sr-only {
  515.     position: absolute;
  516.     width: 1px;
  517.     height: 1px;
  518.     padding: 0;
  519.     margin: -1px;
  520.     overflow: hidden;
  521.     clip: rect(0, 0, 0, 0);
  522.     white-space: nowrap;
  523.     border-width: 0;
  524. }
  525. .text-center {
  526.     text-align: center;
  527. }
复制代码

响应式样式表 (css/responsive.css)
  1. /* 响应式样式 */
  2. @media (max-width: 992px) {
  3.     .hero-content h1 {
  4.         font-size: 2.5rem;
  5.     }
  6.    
  7.     .hero-content p {
  8.         font-size: 1.25rem;
  9.     }
  10. }
  11. @media (max-width: 768px) {
  12.     /* 导航响应式 */
  13.     .nav-toggle {
  14.         display: block;
  15.     }
  16.    
  17.     .nav-menu {
  18.         position: absolute;
  19.         top: 100%;
  20.         left: 0;
  21.         width: 100%;
  22.         background-color: var(--color-white);
  23.         flex-direction: column;
  24.         padding: var(--spacing-unit * 2);
  25.         box-shadow: var(--box-shadow);
  26.         max-height: 0;
  27.         overflow: hidden;
  28.         transition: max-height var(--transition-speed) ease;
  29.     }
  30.    
  31.     .nav-menu.active {
  32.         max-height: 300px;
  33.     }
  34.    
  35.     .nav-menu li {
  36.         margin: var(--spacing-unit) 0;
  37.     }
  38.    
  39.     /* 英雄区域响应式 */
  40.     .hero {
  41.         height: 400px;
  42.     }
  43.    
  44.     .hero-content h1 {
  45.         font-size: 2rem;
  46.     }
  47.    
  48.     .hero-content p {
  49.         font-size: 1rem;
  50.     }
  51.    
  52.     /* 服务区域响应式 */
  53.     .services-grid {
  54.         grid-template-columns: 1fr;
  55.         gap: var(--spacing-unit * 3);
  56.     }
  57.    
  58.     /* 最新作品响应式 */
  59.     .projects-grid {
  60.         grid-template-columns: 1fr;
  61.         gap: var(--spacing-unit * 3);
  62.     }
  63.    
  64.     /* 客户评价响应式 */
  65.     .testimonial-card {
  66.         padding: var(--spacing-unit * 3);
  67.     }
  68.    
  69.     /* 页脚响应式 */
  70.     .footer-content {
  71.         grid-template-columns: 1fr;
  72.         gap: var(--spacing-unit * 5);
  73.     }
  74. }
  75. @media (max-width: 576px) {
  76.     /* 容器响应式 */
  77.     .container {
  78.         padding: 0 var(--spacing-unit);
  79.     }
  80.    
  81.     /* 英雄区域响应式 */
  82.     .hero {
  83.         height: 300px;
  84.     }
  85.    
  86.     .hero-content h1 {
  87.         font-size: 1.5rem;
  88.     }
  89.    
  90.     .hero-content p {
  91.         font-size: 0.9rem;
  92.     }
  93.    
  94.     .btn {
  95.         padding: var(--spacing-unit) var(--spacing-unit * 2);
  96.         font-size: 0.9rem;
  97.     }
  98.    
  99.     /* 服务区域响应式 */
  100.     .service-card {
  101.         padding: var(--spacing-unit * 3);
  102.     }
  103.    
  104.     .service-icon {
  105.         font-size: 2.5rem;
  106.     }
  107.    
  108.     /* 最新作品响应式 */
  109.     .project-info {
  110.         padding: var(--spacing-unit * 2);
  111.     }
  112.    
  113.     .project-info h3 {
  114.         font-size: 1.1rem;
  115.     }
  116.    
  117.     /* 客户评价响应式 */
  118.     .testimonial-author img {
  119.         width: 40px;
  120.         height: 40px;
  121.     }
  122.    
  123.     .testimonial-author h4 {
  124.         font-size: 1rem;
  125.     }
  126.    
  127.     /* 页脚响应式 */
  128.     .footer {
  129.         padding: var(--spacing-unit * 6) 0 var(--spacing-unit * 3);
  130.     }
  131.    
  132.     .footer-about h3,
  133.     .footer-links h3,
  134.     .footer-contact h3 {
  135.         font-size: 1.1rem;
  136.         margin-bottom: var(--spacing-unit * 2);
  137.     }
  138.    
  139.     .footer-about p {
  140.         font-size: 0.9rem;
  141.     }
  142.    
  143.     .footer-links li,
  144.     .footer-contact li {
  145.         font-size: 0.9rem;
  146.     }
  147. }
复制代码

JavaScript文件 (js/main.js)
  1. // 等待DOM加载完成
  2. document.addEventListener('DOMContentLoaded', function() {
  3.     // 导航菜单切换
  4.     const navToggle = document.querySelector('.nav-toggle');
  5.     const navMenu = document.querySelector('.nav-menu');
  6.    
  7.     if (navToggle && navMenu) {
  8.         navToggle.addEventListener('click', function() {
  9.             const expanded = this.getAttribute('aria-expanded') === 'true';
  10.             this.setAttribute('aria-expanded', !expanded);
  11.             navMenu.classList.toggle('active');
  12.         });
  13.         
  14.         // 点击菜单项后关闭菜单
  15.         const navLinks = navMenu.querySelectorAll('a');
  16.         navLinks.forEach(link => {
  17.             link.addEventListener('click', function() {
  18.                 navToggle.setAttribute('aria-expanded', 'false');
  19.                 navMenu.classList.remove('active');
  20.             });
  21.         });
  22.     }
  23.    
  24.     // 客户评价轮播
  25.     const testimonials = document.querySelectorAll('.testimonial-card');
  26.     const prevButton = document.querySelector('.slider-control.prev');
  27.     const nextButton = document.querySelector('.slider-control.next');
  28.    
  29.     if (testimonials.length > 0 && prevButton && nextButton) {
  30.         let currentIndex = 0;
  31.         
  32.         function showTestimonial(index) {
  33.             testimonials.forEach((testimonial, i) => {
  34.                 testimonial.classList.toggle('active', i === index);
  35.             });
  36.         }
  37.         
  38.         function nextTestimonial() {
  39.             currentIndex = (currentIndex + 1) % testimonials.length;
  40.             showTestimonial(currentIndex);
  41.         }
  42.         
  43.         function prevTestimonial() {
  44.             currentIndex = (currentIndex - 1 + testimonials.length) % testimonials.length;
  45.             showTestimonial(currentIndex);
  46.         }
  47.         
  48.         nextButton.addEventListener('click', nextTestimonial);
  49.         prevButton.addEventListener('click', prevTestimonial);
  50.         
  51.         // 自动轮播
  52.         setInterval(nextTestimonial, 5000);
  53.     }
  54.    
  55.     // 平滑滚动
  56.     const links = document.querySelectorAll('a[href^="#"]');
  57.    
  58.     links.forEach(link => {
  59.         link.addEventListener('click', function(e) {
  60.             e.preventDefault();
  61.             
  62.             const targetId = this.getAttribute('href');
  63.             if (targetId === '#') return;
  64.             
  65.             const targetElement = document.querySelector(targetId);
  66.             if (targetElement) {
  67.                 targetElement.scrollIntoView({
  68.                     behavior: 'smooth',
  69.                     block: 'start'
  70.                 });
  71.             }
  72.         });
  73.     });
  74.    
  75.     // 滚动时添加阴影到头部
  76.     const header = document.querySelector('.header');
  77.    
  78.     if (header) {
  79.         window.addEventListener('scroll', function() {
  80.             if (window.scrollY > 50) {
  81.                 header.style.boxShadow = '0 2px 10px rgba(0, 0, 0, 0.1)';
  82.             } else {
  83.                 header.style.boxShadow = '0 2px 5px rgba(0, 0, 0, 0.1)';
  84.             }
  85.         });
  86.     }
  87.    
  88.     // 懒加载图片
  89.     const lazyImages = document.querySelectorAll('img[data-src]');
  90.    
  91.     if ('IntersectionObserver' in window) {
  92.         const imageObserver = new IntersectionObserver((entries, observer) => {
  93.             entries.forEach(entry => {
  94.                 if (entry.isIntersecting) {
  95.                     const img = entry.target;
  96.                     img.src = img.dataset.src;
  97.                     img.removeAttribute('data-src');
  98.                     imageObserver.unobserve(img);
  99.                 }
  100.             });
  101.         });
  102.         
  103.         lazyImages.forEach(img => {
  104.             imageObserver.observe(img);
  105.         });
  106.     } else {
  107.         // 回退到简单的滚动事件
  108.         function lazyLoad() {
  109.             lazyImages.forEach(img => {
  110.                 if (img.getBoundingClientRect().top <= window.innerHeight && img.getBoundingClientRect().bottom >= 0) {
  111.                     img.src = img.dataset.src;
  112.                     img.removeAttribute('data-src');
  113.                 }
  114.             });
  115.         }
  116.         
  117.         window.addEventListener('scroll', lazyLoad);
  118.         window.addEventListener('resize', lazyLoad);
  119.         window.addEventListener('orientationChange', lazyLoad);
  120.         lazyLoad();
  121.     }
  122. });
  123. // 注册Service Worker
  124. if ('serviceWorker' in navigator) {
  125.     window.addEventListener('load', function() {
  126.         navigator.serviceWorker.register('/service-worker.js')
  127.             .then(function(registration) {
  128.                 console.log('ServiceWorker registration successful with scope: ', registration.scope);
  129.             })
  130.             .catch(function(error) {
  131.                 console.log('ServiceWorker registration failed: ', error);
  132.             });
  133.     });
  134. }
复制代码

Service Worker文件 (service-worker.js)
  1. const CACHE_NAME = 'portfolio-cache-v1';
  2. const urlsToCache = [
  3.     '/',
  4.     '/index.html',
  5.     '/about.html',
  6.     '/portfolio.html',
  7.     '/contact.html',
  8.     '/css/normalize.css',
  9.     '/css/style.css',
  10.     '/css/responsive.css',
  11.     '/js/main.js',
  12.     '/js/contact.js',
  13.     '/images/logo.svg',
  14.     '/images/hero-bg.jpg',
  15.     '/images/profile.jpg',
  16.     '/images/projects/project1.jpg',
  17.     '/images/projects/project2.jpg',
  18.     '/images/projects/project3.jpg',
  19.     'https://fonts.googleapis.com/css2?family=Roboto:wght@300;400;700&display=swap',
  20.     'https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css'
  21. ];
  22. // 安装Service Worker并缓存资源
  23. self.addEventListener('install', function(event) {
  24.     event.waitUntil(
  25.         caches.open(CACHE_NAME)
  26.             .then(function(cache) {
  27.                 console.log('Opened cache');
  28.                 return cache.addAll(urlsToCache);
  29.             })
  30.     );
  31. });
  32. // 拦截网络请求并从缓存中响应
  33. self.addEventListener('fetch', function(event) {
  34.     event.respondWith(
  35.         caches.match(event.request)
  36.             .then(function(response) {
  37.                 // 如果资源在缓存中,则返回缓存的资源
  38.                 if (response) {
  39.                     return response;
  40.                 }
  41.                
  42.                 // 否则发起网络请求
  43.                 return fetch(event.request).then(
  44.                     function(response) {
  45.                         // 检查是否收到有效响应
  46.                         if (!response || response.status !== 200 || response.type !== 'basic') {
  47.                             return response;
  48.                         }
  49.                         
  50.                         // 克隆响应,因为响应是流,只能使用一次
  51.                         var responseToCache = response.clone();
  52.                         
  53.                         caches.open(CACHE_NAME)
  54.                             .then(function(cache) {
  55.                                 cache.put(event.request, responseToCache);
  56.                             });
  57.                         
  58.                         return response;
  59.                     }
  60.                 );
  61.             })
  62.     );
  63. });
  64. // 激活新的Service Worker并清理旧缓存
  65. self.addEventListener('activate', function(event) {
  66.     const cacheWhitelist = [CACHE_NAME];
  67.    
  68.     event.waitUntil(
  69.         caches.keys().then(function(cacheNames) {
  70.             return Promise.all(
  71.                 cacheNames.map(function(cacheName) {
  72.                     if (cacheWhitelist.indexOf(cacheName) === -1) {
  73.                         return caches.delete(cacheName);
  74.                     }
  75.                 })
  76.             );
  77.         })
  78.     );
  79. });
复制代码

总结与展望

通过本教程,我们全面了解了HTML5和CSS3的强大功能,以及如何利用它们创建精美、响应式的网页。我们从基础语法开始,逐步深入到高级应用,包括响应式设计原理、Flexbox和Grid布局、CSS3动画、HTML5高级特性等,最后通过一个完整的实战项目将所学知识应用到实践中。

主要知识点回顾

1. HTML5基础:语义化标签的使用表单增强功能多媒体支持(音频和视频)Canvas和SVG图形
2. 语义化标签的使用
3. 表单增强功能
4. 多媒体支持(音频和视频)
5. Canvas和SVG图形
6. CSS3基础:强大的选择器盒模型和布局颜色和背景增强文本效果
7. 强大的选择器
8. 盒模型和布局
9. 颜色和背景增强
10. 文本效果
11. 响应式设计原理:视口设置媒体查询流式布局弹性图片
12. 视口设置
13. 媒体查询
14. 流式布局
15. 弹性图片
16. 响应式布局技术:Flexbox布局Grid布局多列布局
17. Flexbox布局
18. Grid布局
19. 多列布局
20. CSS3高级特性:过渡效果变换效果动画效果自定义属性(CSS变量)
21. 过渡效果
22. 变换效果
23. 动画效果
24. 自定义属性(CSS变量)
25. HTML5高级特性:Canvas绘图SVG图形Web存储Web WorkersGeolocation API
26. Canvas绘图
27. SVG图形
28. Web存储
29. Web Workers
30. Geolocation API
31. 性能优化:图片优化代码优化缓存策略
32. 图片优化
33. 代码优化
34. 缓存策略
35. 最佳实践:代码组织和可维护性CSS最佳实践JavaScript最佳实践可访问性最佳实践
36. 代码组织和可维护性
37. CSS最佳实践
38. JavaScript最佳实践
39. 可访问性最佳实践

HTML5基础:

• 语义化标签的使用
• 表单增强功能
• 多媒体支持(音频和视频)
• Canvas和SVG图形

CSS3基础:

• 强大的选择器
• 盒模型和布局
• 颜色和背景增强
• 文本效果

响应式设计原理:

• 视口设置
• 媒体查询
• 流式布局
• 弹性图片

响应式布局技术:

• Flexbox布局
• Grid布局
• 多列布局

CSS3高级特性:

• 过渡效果
• 变换效果
• 动画效果
• 自定义属性(CSS变量)

HTML5高级特性:

• Canvas绘图
• SVG图形
• Web存储
• Web Workers
• Geolocation API

性能优化:

• 图片优化
• 代码优化
• 缓存策略

最佳实践:

• 代码组织和可维护性
• CSS最佳实践
• JavaScript最佳实践
• 可访问性最佳实践

行业趋势与未来发展

随着技术的不断发展,网页开发领域也在持续演进。以下是一些当前和未来的趋势:

1. Web组件:通过自定义元素、Shadow DOM和HTML模板创建可重用的组件,提高代码的可维护性和复用性。
2. Progressive Web Apps (PWA):结合Web和原生应用的优势,提供离线功能、推送通知和类似原生应用的体验。
3. WebAssembly:允许在浏览器中运行编译自其他语言(如C++、Rust)的代码,提供接近原生的性能。
4. CSS Houdini:一组新的API,允许开发者直接访问CSS引擎,创建自定义的CSS属性和值。
5. 容器查询:类似于媒体查询,但基于容器的大小而不是视口的大小,使组件级别的响应式设计更加容易。
6. WebXR:用于创建虚拟现实(VR)和增强现实(AR)体验的API。
7. AI驱动的开发:人工智能工具正在改变开发者的工作方式,从代码生成到自动化测试。

Web组件:通过自定义元素、Shadow DOM和HTML模板创建可重用的组件,提高代码的可维护性和复用性。

Progressive Web Apps (PWA):结合Web和原生应用的优势,提供离线功能、推送通知和类似原生应用的体验。

WebAssembly:允许在浏览器中运行编译自其他语言(如C++、Rust)的代码,提供接近原生的性能。

CSS Houdini:一组新的API,允许开发者直接访问CSS引擎,创建自定义的CSS属性和值。

容器查询:类似于媒体查询,但基于容器的大小而不是视口的大小,使组件级别的响应式设计更加容易。

WebXR:用于创建虚拟现实(VR)和增强现实(AR)体验的API。

AI驱动的开发:人工智能工具正在改变开发者的工作方式,从代码生成到自动化测试。

持续学习建议

网页开发是一个快速发展的领域,持续学习是保持竞争力的关键。以下是一些建议:

1. 关注标准发展:跟踪W3C、WHATWG等组织的工作,了解HTML、CSS和JavaScript的最新发展。
2. 参与社区:加入开发者社区,如Stack Overflow、GitHub、Reddit的r/webdev等,与其他开发者交流经验和知识。
3. 实践项目:通过实际项目应用所学知识,从简单的个人网站到复杂的应用程序。
4. 阅读源码:研究优秀的开源项目,了解最佳实践和设计模式。
5. 参加培训和会议:参加在线课程、研讨会和技术会议,学习最新的技术和趋势。
6. 教授他人:通过写博客、做演讲或指导初学者来巩固自己的知识。

关注标准发展:跟踪W3C、WHATWG等组织的工作,了解HTML、CSS和JavaScript的最新发展。

参与社区:加入开发者社区,如Stack Overflow、GitHub、Reddit的r/webdev等,与其他开发者交流经验和知识。

实践项目:通过实际项目应用所学知识,从简单的个人网站到复杂的应用程序。

阅读源码:研究优秀的开源项目,了解最佳实践和设计模式。

参加培训和会议:参加在线课程、研讨会和技术会议,学习最新的技术和趋势。

教授他人:通过写博客、做演讲或指导初学者来巩固自己的知识。

结语

HTML5和CSS3为现代网页开发提供了强大的工具,使开发者能够创建美观、功能丰富且适应各种设备的网站。通过本教程的学习,您已经掌握了从基础到高级的知识,可以开始创建自己的响应式网站。

记住,网页开发是一个不断学习和实践的过程。随着技术的不断发展,保持好奇心和学习热情是成为优秀开发者的关键。祝您在网页开发的道路上取得成功!
「七転び八起き(ななころびやおき)」
回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则