一、html5标签

1.文档结构

标签类别 标签 描述 常用属性
文档结构 <!DOCTYPE> 定义文档类型 (无属性)
<html> HTML文档根元素 lang
<head> 文档元信息容器 (无常用属性)
<title> 文档标题 (无属性)
<body> 文档内容容器 class, id, style
1
2
3
4
5
6
7
8
9
<!DOCTYPE html>		声明为html文件	
<html lang="en">
<head>
<title>Document</title>
</head>
<body>

</body>
</html>

2.元信息

标签类别 标签 描述 常用属性
元信息 <meta> 文档元数据 charset, name, content
<link> 链接外部资源 rel, href, type
<style> 内部样式表 type, media
<script> 客户端脚本 src, type, defer, async
<base> 默认链接目标 href, target
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<!-- 核心必备:编码声明 -->
<meta charset="UTF-8">
<!-- 核心必备:移动端适配 -->
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<!-- 基准地址:所有相对URL地址都会进行拼接 -->
<base href="https://www.example.com/static/">
<!-- 实际引入地址:https://www.example.com/static/css/style.css 注:如果是绝对地址不会触发base标签!!!!-->
<link rel="stylesheet" href="css/style.css">
<title>简化版 HTML 元信息示例</title>
</head>
<body>
</body>
</html>

3.内容分区(了解即可)

标签类别 标签 描述 常用属性
内容分区 <header> 页眉 class, id
<nav> 导航链接 class, id
<main> 主要内容 class, id
<section> 独立部分 class, id
<article> 独立文章 class, id
<aside> 侧边内容 class, id
<footer> 页脚 class, id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="zh-CN">
<!-- 元信息头部:存储不可视元数据 -->
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
<!-- 页面级头部:可视内容,包含logo和标题 -->
<header class="page-header" style="background-color: #f5f5f5; padding: 20px;">
<h1>我的个人博客</h1>
<img src="logo.png" alt="博客logo" width="100">
</header>

<!-- 区块级头部:文章区块的头部 -->
<article>
<header class="article-header" id="article1-header">
<h2>HTML 内容分区标签详解</h2>
<p>发布时间:2026-01-02</p>
</header>
<p>文章正文内容...</p>
</article>
</body>
</html>

4.文本内容

文本内容 <h1>-<h6> 标题 class, id, style
<p> 段落 class, id, style
<br> 换行,强制 class, style
<wbr> 当容器溢出在换行,非强制
<hr> 水平线 class, id, style
<pre> 预格式化文本,保留原始格式,类似于java “”” “”” class, id
<blockquote> 块引用,默认视觉效果:浏览器会给引用块添加 左侧外边距 / 内边距(通常为 40px 左右) cite, class, id
<q> 行内引用 cite
内联文本 <em> 强调文本 class, id, style
<strong> 重要文本 class, id, style
<mark> 高亮文本 class, id, style
<small> 小字文本 class, id, style
<del> 删除文本,内容会加上中划线 cite, datetime
<ins> 插入文本 cite, datetime
<sub> 下标 class, id
<sup> 上标 class, id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<div class="article">
<h1>HTML 文本标签详解</h1>
<h2>一、块级文本标签的使用</h2>
<p>块级文本标签主要用于搭建页面文本的整体结构,让内容层次清晰,便于阅读和搜索引擎识别。</p>
<!--默认视觉效果:浏览器会给引用块添加左侧外边距 / 内边距(通常为 40px 左右),部分浏览器会附带轻微边框或斜体样式,整体独占一行(块级标签特性),上 下与其他内容保留间距。-->
<blockquote cite="https://www.w3.org/TR/html52/">HTML 文本标签应遵循语义化原则,优先使用对应功能的标签而非格式化标签。</blockquote>
<pre> <!-- 此时不会变为1行,而是按照这个样式!!!-->
这里是预格式化的代码示例
var text = "Hello, World!";
console.log(text);
</pre>
<hr>
<h2>二、行内文本标签的使用</h2>
<del>删除文本</del>
<mark style="color:aquamarine;">sadsd</mark>
</div>

5.链接

标签类别 标签 描述 常用属性
链接 <a> 超链接 href 跳转地址, target 目标 , rel 引用 , title 标题,鼠标悬浮即可显示

取值说明:

  1. 绝对 URL(如 https://www.baidu.comhttps://example.com/article.html
  2. 相对 URL(如 index.html./pages/about.html../images/logo.png
  3. 锚点(如 #top#content#article-1001) 如: <pre id="name">1</pre> <a href="#name"></a> 此时点击a标签跳转到pre标签
  4. 邮箱(如 mailto:zhangsan@example.com
  5. 电话(如 tel:138XXXX1234
  6. 空值(href=""href="#"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>超链接</title>
<style>
a{
text-decoration: none;
}
</style>
</head>
<body>
<a href="E:\网页制作\web4.html">点我跳转</a>
<br><a href="E:\网页制作\web3.html" target="_blank">新文件</a>
<a href="tel:15304544307">111</a>
</body>
</html>

6.多媒体

多媒体 <img> 图像 src, alt, width, height
<audio> 音频 src, controls, autoplay, loop
<video> 视频 src, controls, width, height, poster
<source> 媒体源 src, type
<track> 字幕轨道 src, kind, srclang, label
<canvas> 图形绘制 width, height, id
<svg> SVG图形 width, height, viewBox

(1)img

<img> 是单标签,src 和 alt 为必备属性,确保图片正常展示和语义化。

属性名 取值说明 核心作用
src 绝对 URL / 相对 URL(图片地址,如 ./images/photo.jpghttps://example.com/logo.png 指定图片资源地址,是图片展示的核心属性,无 src 则图片无法显示
alt 文本描述(如 网站 Logo海边风景照片 1. 图片加载失败时显示替代文本;2. 辅助屏幕阅读器识别图片内容;3. 提升 SEO 效果(必备,语义化要求)
width 像素值(如 300)、百分比(如 50% 设置图片宽度,仅设置 width 时,高度会自动等比例缩放,避免图片变形
height 像素值(如 200)、百分比(如 30% 设置图片高度,不建议同时强制设置 widthheight(易导致图片变形,除非图片比例固定)
title 文本描述 鼠标悬浮在图片上时显示提示文本,补充图片说明
loading eager(默认,立即加载)、lazy(懒加载) 控制图片加载策略,lazy 用于长页面非首屏图片,提升页面加载速度
srcset/sizes 多分辨率图片地址 / 图片显示尺寸条件 适配不同设备分辨率(如手机、平板、电脑),实现响应式图片展示
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>图片标签示例</title>
</head>
<body>
<div class="img-container">
<h3>基础图片展示(必备属性 src + alt)</h3>
<img
src="./images/sea.jpg"
alt="海边日落风景,海面波光粼粼,远处有帆船"
width="600"
title="海边日落"
>
</div>
<div class="img-container">
<h3>懒加载图片(非首屏推荐)</h3>
<img
src="./images/mountain.jpg"
alt="高山森林风景,山顶覆盖积雪"
width="600"
loading="lazy"
title="高山雪景"
>
</div>
</body>
</html>

(2)audio

属性名 取值说明 核心作用
src 音频文件 URL(如 ./audio/music.mp3 指定音频资源地址,可直接绑定单一格式音频
controls 无需赋值(存在即生效) 显示浏览器原生音频控制栏(播放 / 暂停、进度条、音量调节),无此属性则音频无法手动控制
autoplay 无需赋值(存在即生效) 页面加载完成后自动播放音频(现代浏览器大多限制,需配合 muted 静音自动播放)
loop 无需赋值(存在即生效) 音频播放完毕后循环播放
muted 无需赋值(存在即生效) 音频默认静音播放,可解决 autoplay 被浏览器限制的问题
preload none(不预加载)、metadata(仅预加载元数据:时长、大小)、auto(自动预加载全部音频) 控制音频预加载策略,建议设置 metadata,平衡加载速度和用户体验

(3)video

video用于视频播放

属性名 取值说明 核心作用
src 视频文件 URL(如 ./video/movie.mp4 指定视频资源地址,可直接绑定单一格式视频
controls 无需赋值(存在即生效) 显示浏览器原生视频控制栏(播放 / 暂停、进度条、音量、全屏等)
autoplay 无需赋值(存在即生效) 页面加载完成后自动播放视频(需配合 muted 才能在现代浏览器生效)
loop 无需赋值(存在即生效) 视频播放完毕后循环播放
muted 无需赋值(存在即生效) 视频默认静音播放,解决 autoplay 被限制的问题
preload none/metadata/auto 控制视频预加载策略,建议设置 metadata(仅预加载时长、分辨率等元数据)
width/height 像素值(如 640/480 设置视频尺寸,仅设置 width 时,高度自动等比例缩放,避免视频变形
poster 图片 URL(如 ./images/video_cover.jpg 设置视频封面图,在视频未播放(加载中 / 未点击)时显示,提升用户体验
1
2
3
4
5
6
7
8
9
10
11
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<video src="../video/1.mp4" controls muted style="width: 600px;height: 600px;" poster="../img/3.png"></video>
</body>
</html>

7.列表

列表 <ul> 无序列表 class, id, style
<ol> 有序列表 class, id, start 序号开始数字, type 列表序号类型,reversed 颠倒列表
<li> 列表项 class, id, value
<dl> 描述列表 class, id
<dt> 描述术语 class, id
<dd 跟随dt标签,自动空两行> 描述内容 class, id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>无序列表</title>
</head>
<body>
<ul>
<li>香蕉</li>
<li>黄瓜</li>
<li>茄子</li>
<li>蜜桃</li>
</ul>
<ol reversed type="1" start="5">
<!-- reversed 颠倒的 -->
<!-- 有序列表 -->
<li>绿茶</li>
<li>冰红茶</li>
<li>柚子茶</li>
<li>乌龙茶</li>
</ol>
<dl>
<!-- 自定义排序 -->
<dt>所属学院</dt>
<dd>软件工程</dd>
<dd>前端开发</dd>
<dt>所属专业</dt>
<dd>信息工程</dd>
</dl>
<hr>
</body>
</html>

8.表格

表格 <table> 表格 class, id, border, width,border-collapse: collapse 合并表格间距
<caption> 表格标题 class, id
<tr> 表格行 class, id, style
<th> 表头单元格 colspan="列数" 列合并, rowspan="行数" 行和并 , scope
<td> 数据单元格 colspan, rowspan
<thead> 表头区域 class, id
<tbody> 表体区域 class, id
<tfoot> 表尾区域 class, id
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>基础表格示例</title>
<style>
body { padding: 20px; }
/* 表格基础样式:边框合并、间距优化 */
table {
border-collapse: collapse; /* 合并单元格边框(关键) */
width: 600px; /* 表格宽度 */
margin: 20px 0;
text-align: center; /* 单元格内容居中 */
}
th, td {
border: 1px solid #ccc; /* 单元格边框 */
padding: 10px; /* 单元格内边距,提升可读性 */
}
th {
background-color: #f5f5f5; /* 表头背景色,区分普通单元格 */
}
</style>
</head>
<body>
<h3>学生成绩表(基础结构)</h3>
<table>
<tr>
<!-- colspan 合并列,"5"表示合并5列 -->
<th colspan="5">学生成绩</th>
</tr>
<!-- 第一行:表头 -->
<tr>
<th>姓名</th>
<th>语文</th>
<th>数学</th>
<th>英语</th>
<th>性别</th>
</tr>
<!-- 第二行:普通数据 -->
<tr>
<td>张三</td>
<td>92</td>
<td>98</td>
<td>89</td>
<!-- 从自己开始,此列两行和为1行 -->
<td rowspan="2"></td>
</tr>
<!-- 第三行:普通数据 -->
<tr>
<td>李四</td>
<td>88</td>
<td>90</td>
<td>95</td>
</tr>
<tr>
<td>王五</td>
<td>90</td>
<td>90</td>
<td>100</td>
<td></td>
</tr>
</table>
</body>
</html>

9.表单

表单 <form> 表单容器 action, method, name, target
<input> 输入控件 type, name, value, placeholder, required
<textarea> 多行文本输入 name, rows, cols, placeholder
<button> 按钮 type, name, value, disabled
<select> 下拉列表 name, multiple, size
<option> 下拉选项 value, selected, disabled
<label> 表单标签 for
<fieldset> 表单分组 name, disabled
<legend> 分组标题 (无常用属性)

(1)form

<form> 是表单的外层容器,负责定义数据提交的规则,核心属性如下:

属性名 取值说明 核心作用
action 绝对 URL / 相对 URL(如 ./login.phphttps://example.com/submit 指定表单数据提交的目标地址(服务器接口),若留空则提交至当前页面
method get(默认)/ post 定义表单数据的提交方式:1. get:数据拼接在 URL 后(可见,有长度限制,适合查询)2. post:数据在请求体中(不可见,无长度限制,适合提交敏感 / 大量数据)
enctype 1. application/x-www-form-urlencoded(默认,普通数据提交)2. multipart/form-data(文件上传时必须设置)3. text/plain(纯文本提交,极少使用) 定义表单数据的编码方式,上传文件时必须设置为 multipart/form-data
target _self(默认)/ _blank / _parent / _top 定义提交后服务器响应的打开方式,与 <a> 标签的 target 属性用法一致
novalidate 无需赋值(存在即生效) 禁用浏览器原生的表单验证,仅使用自定义验

(2)input

<input> 是单标签,通过 type 属性切换不同功能的表单控件,常用 type 取值如下:

type 取值 控件类型 核心用途 关键属性
text 单行文本输入框 收集普通文本(用户名、姓名等) placeholder(提示文本)、maxlength(最大输入长度)、required(必填)
password 密码输入框 收集敏感密码(输入内容隐藏为圆点 / 星号) text,额外可设置 autocomplete="new-password" 关闭密码自动填充
radio 单选按钮 从多个选项中选择一个(性别、是否同意等) name(必须相同,实现互斥选择)、value(提交的实际值)、checked(默认选中)
checkbox 复选框 从多个选项中选择多个(兴趣爱好、权限等) name(建议设置为数组格式 xxx[])、valuechecked(默认选中)
file 文件上传框 上传本地文件(头像、文档等) accept(限制文件类型,如 image/*.pdf)、multiple(允许多文件上传)
email 邮箱输入框 收集邮箱地址,浏览器原生验证格式 text,额外支持原生邮箱格式校验(如必须包含 @
tel 电话输入框 收集电话号码,移动端唤起数字键盘 无特殊验证,仅优化移动端输入体验
date 日期选择 选择日期 年月日
number 数字输入框 收集数字,唤起数字键盘,支持步长控制 min(最小值)、max(最大值)、step(步长)
submit 提交按钮 触发表单提交,将数据发送至 action 地址 value(按钮显示文本)
reset 重置按钮 重置表单所有控件为默认值 value(按钮显示文本)
button 普通按钮 绑定自定义 JS 事件,不触发表单提交 / 重置 value(按钮显示文本)
hidden 隐藏域 提交无需用户输入的隐藏数据(如表单标识) value(提交的实际值)

input属性 注:这些属性不止input,select和texteare同样有

属性 值类型 描述 示例
type 字符串 输入类型(最重要) text, password, email
name 字符串 表单字段名称 username, email
value 字符串 初始值/默认值 value="默认文本"
placeholder 字符串 提示文本(占位符) placeholder="请输入..."
required 布尔 必填字段 required
disabled 布尔 禁用字段 disabled
readonly 布尔 只读字段 readonly
autocomplete 字符串 自动完成 on, off, username
autofocus 布尔 自动聚焦 autofocus
maxlength 数字 最大字符数 maxlength="10"
minlength 数字 最小字符数 minlength="3"

(3)select + option

select属性

属性 值类型 描述 示例
name 字符串 表单字段名称(必需) name="country"
id 字符串 唯一标识符 id="countrySelect"

option属性

属性 描述 示例
value 选项值(提交时用) value="us"
selected 默认选中 selected
disabled 禁用选项 disabled
label 替代显示文本 label="美国"
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<select>
<option value="">出生年份</option>
<option value="">2004</option>
<option value="">2006</option>
<option value="">2007</option>
</select>
<select>
<option value="">月份</option>
<option value="">7</option>
<option value="">2</option>
<option value="">8</option>
</select>
<select>
<option value=""></option>
<option value="">2</option>
<option value="">7</option>
<option value="">8</option>
</select>

(4)textarea

属性 值类型 描述 示例
name 字符串 表单字段名称(必需) name="content"
id 字符串 唯一标识符 id="message"
rows 数字 可见行数 rows="5"
cols 数字 可见列数(字符数) cols="50"
placeholder 字符串 占位提示文本 placeholder="请输入..."
required 布尔 必填字段 required
disabled 布尔 禁用文本域 disabled

(5)label

提升点击区域

使用方式: <lable><input type="radio">男</label> 此时点击男也能选中复选框

10.可折叠内容

标签/属性 描述 示例
<details> 可折叠内容容器 <details>内容</details>
open 属性 默认展开状态 <details open>
<summary> 子属性 折叠面板的标题 <summary>点击查看</summary>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<div class="faq">
<h2>常见问题</h2>

<details>
<summary>如何注册账号?</summary>
<div class="faq-content">
<p>访问注册页面,填写邮箱和密码即可完成注册。</p>
<ol>
<li>点击右上角"注册"按钮</li>
<li>输入邮箱地址</li>
<li>设置密码</li>
<li>完成邮箱验证</li>
</ol>
</div>
</details>

<details>
<summary>忘记密码怎么办?</summary>
<div class="faq-content">
<p>在登录页面点击"忘记密码",按照提示操作即可重置密码。</p>
</div>
</details>

<details>
<summary>如何联系客服?</summary>
<div class="faq-content">
<p>客服电话: 400-123-4567</p>
<p>在线客服: 工作日 9:00-18:00</p>
<p>邮箱: support@example.com</p>
</div>
</details>
</details>
</div>

<!-- 2. 产品特性展示 -->
<div class="product-features">
<details>
<summary>
<span class="feature-icon">🚀</span>
<span class="feature-title">高性能</span>
</summary>
<p>采用最新处理器,提供流畅的使用体验。</p>
<ul>
<li>处理速度提升 40%</li>
<li>支持多任务并行处理</li>
<li>能耗降低 30%</li>
</ul>
</details>

<details>
<summary>
<span class="feature-icon">🔒</span>
<span class="feature-title">安全可靠</span>
</summary>
<p>多层安全防护,保障数据安全。</p>
</details>
</div>

二、css3样式

使用流程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>文本排版样式示例</title>
<!-- 使用style标签
*表示通配符,所有标签都会生效
-->
<style>
*{
...
}
标签名{}
.类名{}
#id名{}
</style>
</head>
<body>
</body>
</html>

1.文本样式

样式类别 核心属性 核心作用 取值说明(常用)
文本外观 color 设置文本颜色 十六进制(#333)、RGB(rgb(51,51,51))、颜色名(black
font-family 设置文本字体 字体名("Microsoft Yahei"Arial)、通用字体族(sans-serif
font-size 设置文本大小 像素(14px)、rem(1.2rem)、百分比(100%
font-weight 设置文本粗细 关键字(normalbold)、数字(400= 正常、700= 加粗)
font-style 设置文本样式(斜体 / 正常) normal(正常)、italic(斜体)、oblique(倾斜)
文本排版 text-align 设置文本水平对齐方式 left(左对齐)、center(居中)、right(右对齐)、justify(两端对齐)
line-height 设置文本行高(行间距) 数字(1.8)、像素(24px)、百分比(150%
text-indent 设置文本首行缩进 像素(28px)、em(2em,推荐,对应 2 个字符宽度)
letter-spacing 设置字符间距(字间距) 像素(2px)、负值(-1px,缩小间距)
word-spacing 设置单词间距(仅对英文有效) 像素(5px)、负值(-2px
文本装饰与交互 text-decoration 设置文本装饰线(下划线 / 删除线等) none(无装饰)、underline(下划线)、line-through(删除线)
text-transform 转换文本大小写(仅对英文有效) noneuppercase(大写)、lowercase(小写)、capitalize(首字母大写)
white-space 控制文本空白符(空格 / 换行)的处理方式 normal(默认折叠)、nowrap(不换行)、pre(保留原格式)
overflow-wrap 控制长文本 / URL 自动换行 normalbreak-word(强制换行,避免溢出)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>文本排版样式示例</title>
<style>
body { padding: 20px; max-width: 800px; margin: 0 auto; }
.text-title {
font-size: 24px;
font-weight: 700;
color: #222;
text-align: center;
line-height: 2;
letter-spacing: 2px;
}
.text-paragraph {
font-family: "Microsoft Yahei", sans-serif;
font-size: 16px;
line-height: 1.8;
text-indent: 2em;
text-align: left;
letter-spacing: 0.5px;
color: #333;
margin: 12px 0;
}
.text-right {
text-align: right;
font-size: 14px;
color: #666;
line-height: 1.5;
margin-top: 20px;
}
</style>
</head>
<body>
<h2 class="text-title">CSS 文本排版的重要性</h2>
<p class="text-paragraph">文本排版是网页开发中不可或缺的一部分,良好的排版能够显著提升用户的阅读体验。合适的行高、首行缩进和字符间距,能够让大段正文更易读,减轻用户的视觉疲劳。</p>
<p class="text-paragraph">在中文网页中,首行缩进2个字符是传统排版习惯,通过CSS的text-indent属性可以轻松实现。而行高的设置尤为关键,过窄的行高会导致文本拥挤,过宽的行高则会让文本失去连贯性。</p>
<p class="text-right">2026年1月3日</p>
</body>
</html>

2.背景样式

样式类别 核心属性 核心作用 取值说明(常用)
背景基础 background-color 设置元素背景颜色 十六进制(#f5f5f5)、RGB(rgb(245,245,245))、transparent(透明,默认)
背景图片 background-image 设置元素背景图片 url(./bg.jpg)(本地图片)、url(https://xxx.com/bg.jpg)(网络图片)、none(无背景图,默认)
background-repeat 控制背景图片是否重复及重复方式 no-repeat(不重复)、repeat(默认,平铺)、repeat-x(水平重复)、repeat-y(垂直重复)
background-size 控制背景图片的尺寸大小 auto(默认,原图尺寸)、cover(覆盖元素,可能裁剪)、contain(完整显示,可能留白)、像素(300px 200px)、百分比(100% 50%
背景定位与裁剪 background-position 控制背景图片在元素中的位置 关键字(centertop left)、像素(50px 30px)、百分比(50% 50%
background-attachment 控制背景图片是否随页面 / 元素滚动 scroll(默认,随元素滚动)、fixed(固定视口,不随页面滚动)、local(随元素内容滚动)
background-clip 控制背景的显示范围(裁剪边界) border-box(默认,延伸至边框)、padding-box(延伸至内边距)、content-box(仅内容区域)
background-origin 控制背景图片的起始定位点 background-clip 取值一致,默认 padding-box
简写属性 background 整合所有背景属性,简化代码 顺序:color > image > repeat > position > size > attachmentsize 需跟在 position 后加 / 分隔)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
body{
background-image: url(../img/R-C.jpg);
background-repeat: no-repeat;
background-attachment: fixed;
}
.box{
text-align: center;
font-size: 40px;
}
</style>
</head>
<body>
<p class="box">背景图不动了</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
<p>测试</p>
</body>
</html>

3.字体图标

在网页显示的图标,可以在aliyun选择,这里使用Font Awesome 字体图标库

核心格式: <i class="fa + 具体图标class"></i>

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>字体图标简单效果</title>
<!-- 1. 引入 Font Awesome 字体图标库(CDN 方式,无需本地下载) -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/font-awesome@4.7.0/css/font-awesome.min.css">
<style>
/* 简单样式美化,突出图标效果 */
.icon-demo {
width: 80%;
margin: 50px auto;
text-align: center;
}
/* 字体图标可直接通过 CSS 修改大小、颜色、阴影 */
.fa {
font-size: 32px; /* 图标大小 */
margin: 0 15px; /* 图标间距 */
color: #0066cc; /* 图标颜色 */
cursor: pointer; /* 鼠标悬浮手型 */
}
/* 悬浮变色效果(可选,增强交互) */
.fa:hover {
color: #dc3545;
transform: scale(1.1); /* 轻微放大 */
transition: all 0.3s ease;
}
.icon-text {
margin-top: 10px;
font-size: 14px;
color: #333;
}
</style>
</head>
<body>
<div class="icon-demo">
<!-- 2. 使用字体图标:核心格式 <i class="fa + 具体图标class"></i> -->
<i class="fa fa-home"></i>
<i class="fa fa-user"></i>
<i class="fa fa-search"></i>
<i class="fa fa-heart"></i>
<i class="fa fa-share-alt"></i>

<div class="icon-text">点击/悬浮图标可看交互效果</div>
</div>
</body>
</html>

4.显示模式转换

在html的元素一共有三种模式: 块元素、行内元素、行内块元素,可以使用 display: 模式 进行转换

类别 核心特点 常见HTML标签 默认样式示例
块级元素 独占一行;可设置宽高和内外边距;宽度默认为父级的100% <div>, <h1>-<h6>, <p>, <ul>, <ol>, <li>, <table>, <form>, <section>, <article>, <header>, <footer>, <nav> display: block;
行内元素 不独占一行,与其他行内元素同行排列;不可设置宽高;上下外边距无效;大小由内容撑开 <span>, <a>, <strong>, <em>, <i>, <b>, <label>, <br>, <sup>, <sub> display: inline;
行内块元素 结合两者特点:不独占一行,但可以设置宽高和内外边距 <img>, <input>, <button>, <select>, <textarea>, <video> display: inline-block;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
p{
display: inline; #行内
text-indent: 2em;
letter-spacing: 2px;
text-decoration:underline;
}
</style>
</head>
<body>
<p>文章,1984年6月26日出生于陕西省西安市雁塔区,毕业于中央戏剧学院表演系,中国内地男演员、导演[1]。</p>
</body>
</html>

5.盒子模型

top 顶部、left 左边、 right 右边、bottom 底部

属性 值类型 描述 示例
width 长度值 宽度 width: 100px; width: 50%; width: auto;
height 长度值 高度 height: 200px; height: 100vh;
min-width 长度值 最小宽度 min-width: 300px;
max-width 长度值 最大宽度 max-width: 1200px;
min-height 长度值 最小高度 min-height: 100px;
max-height 长度值 最大高度 max-height: 500px;
margin 长度值 外边距 margin: 10px; margin: 10px 20px;
padding 长度值 内边距 padding: 15px; padding: 10px 20px 15px 25px;
border 复合值 边框 border: 1px solid #ccc;
border-width 长度值 边框宽度 border-width: 2px;
border-style 关键词 边框样式 border-style: solid; border-style: dashed;
border-color 颜色值 边框颜色 border-color: red;
border-radius 长度值 边框圆角 border-radius: 5px; border-radius: 50%;
box-sizing 关键词 盒模型计算 box-sizing: border-box; box-sizing: content-box;
box-shadow 阴影值 盒子阴影 box-shadow: 2px 2px 10px rgba(0,0,0,0.1);
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title制作网页</title>
<style>
/*盒子*/
.a{
width: 500px;
height:400px;
color: chartreuse;
background-color: firebrick;
margin:30px auto;

/* 变大 */
padding:20px;
border: 10px solid #000;

/* 第一个左边的 第二个上边的 */
/* margin:20px 15px; */

/* 盒子尺寸不会加上padding尺寸和border尺寸 */
box-sizing:border-box;
}
strong{
text-align:center;
line-height:500px;

}
.b{
display: inline-block;
width: 200px;
height: 200px;
background-color: aqua;
/* 规则:从左上角顺时针赋值,没有取值的角与对角线相同 */
/* 三个值 */
border-radius: 30px 40px 60px;
text-align: center;
}
.c{
display: inline-block;
background-color: antiquewhite;
text-align: center;
margin-left: 100px;
width: 200px;
height: 200px;
/* 两个值 */

}
</style>
</head>
<body>
<div class="a">
<strong> 我是一个盒子,可用装东西 </strong>
</div>
<hr>
div圆角设置
<div class="b">3个值</div>
<div class="c">2个值</div>
<div class="e"></div>
</body>
</html>

(1)外边距合并与塌陷

合并:当有两个上下的div元素,一个设置margin-bottom:100px;另一个设置margin-top:40px;

此时margin-top的标签会失效,只会取相邻的最大值!!!!!!!!!!

塌陷:当给子级添加外边距,此时父级也会生效,但只想子级移动。

解决办法:1.取消子级margin,给父级添加padding和box-sizing标签。

2.父级设置overflow:hidden; 3.父级设置border-top;

(2)元素溢出

控制溢出元素的内容的显示方式。overflow 溢出;

格式:overflow = 属性值; 属性值:hidden 隐藏; scroll 溢出滚动(有没有溢出都有); auto 溢出滚动;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.a{
width: 300px;
height: 200px;
background-color: aqua;
/* 超出隐藏 */
/* overflow: hidden; */
/* 添加滚动条 */
overflow: scroll;
}
.b{
width: 100px;
height: 100px;
background-color: aquamarine;
/* 这个外边距数值大,只会生成这个 */
margin-bottom: 30px;
}
.c{
width: 100px;
height: 100px;
background-color: rgb(4, 73, 50);
/* 这个不会生效,因为上面数值更大 */
margin-top:10px;
}
.d{
width: 200px;
height: 200px;
background-color: bisque;
/* 父级加上padding和box-sizing标签就不生效子级属性 */
padding-top:50px;
box-sizing:border-box;
}
.e{
width: 50px;
height: 50px;
background-color: blue;
/* 此时父级也会继承这个属性,但只想移动子级 */
margin:30px;

}

</style>
</head>
<body>
<div class="a">文字溢出
文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出文字
溢出文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出
文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出
文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出
文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出
文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出
文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出
文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出文字溢出
</div>
<hr>
外边距合并
<div class="b"></div>
<div class="c"></div>

<hr>
外边距塌陷
<div class="d"><div class="e"></div></div>
</body>
</html>

(3)元素显示

visibility: visible 元素可见,并占位置

visibility: hidden 元素不可见,并占位置

(4)盒子阴影

属性值:x偏移量 y偏移量 模糊半径 扩散半径 颜色 内外阴影;

如:box-shadow:10px 10px 5px 1px raba(0,0,0,.5) inset;

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
.box{
width: 500px;
height: 500px;
border:1px solid black;
margin:40px auto;
}
.box:hover{
/* 盒子阴影设置: 阴影越大越右 阴影越大越下 越大阴影越模糊 越大阴影越大 颜色 */
box-shadow: 16px 19px 12px 1px rgb(126, 124, 124);
}
</style>
</head>
<body>
<div class="box"></div>
</body>
</html>

(5)盒子圆角

border-radius: 上左角度数 上右角度数 下右角度数 下左角度数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
/* 1个值:四个角的圆角半径完全相同 */
.border-radius-1 {
border-radius: 10px; /* 上左、上右、下右、下左均为 10px */
}

/* 2个值:第1个值对应 上左/下右,第2个值对应 上右/下左(对角线对称) */
.border-radius-2 {
border-radius: 10px 20px; /* 上左/下右:10px;上右/下左:20px */
}

/* 3个值:第1个=上左,第2个=上右/下左,第3个=下右(下左继承上右的值) */
.border-radius-3 {
border-radius: 10px 20px 30px; /* 上左:10px;上右/下左:20px;下右:30px */
}

/* 4个值:顺时针依次对应 上左→上右→下右→下左(四个角独立设置) */
.border-radius-4 {
border-radius: 10px 20px 30px 40px; /* 四个角分别设置,无对称补充 */
}

6.标准流与浮动

标准流又称「普通流 / 文档流」,是浏览器渲染 HTML 元素的默认方式,所有元素在页面中都会遵循标准流的规则进行排列,无需额外设置布局属性。

1. 标准流的两大核心规则

(1)块级元素(Block-level Element):垂直独占一行排列

常见块级元素:divh1-h6pul/liformsection 等。

核心特性:

  • 垂直方向:从上到下依次排列,每个块级元素独占一行,无法与其他元素同行显示;
  • 水平方向:默认撑满父元素的整个宽度(width: 100%);
  • 可设置 widthheightmarginpaddingborder,尺寸可控;
  • 嵌套时:子块级元素默认受父块级元素的宽度限制,高度由内容撑开。

(2)行内元素(Inline Element):水平从左到右排列

常见行内元素:spanaemstronglabelimg(特殊:行内块元素)等。

核心特性:

  • 水平方向:从左到右依次排列,一行排满后自动换行,不会独占一行;
  • 垂直方向:对齐方式为「基线对齐」(可通过 vertical-align 调整);
  • 尺寸限制:默认无法设置 widthheight,尺寸由内容本身撑开;
  • 边距限制:margin 仅左右生效、上下不生效;padding 上下生效但不会撑大父元素的高度,不会影响相邻元素的垂直布局;
  • 行内块元素(inline-block):兼具行内元素(同行排列)和块级元素(可设宽高 / 边距)的特性,img 标签默认是行内块元素。

2.浮动(过时)

浮动是 CSS 中用于打破标准流排列规则的属性,通过 float 属性让元素脱离标准流的默认排列,实现同行显示、环绕排列等复杂布局,是传统布局中实现多列布局的核心方案。

取值 核心作用
left 元素向左浮动,靠父元素的左侧排列,脱离标准流
right 元素向右浮动,靠父元素的右侧排列,脱离标准流
none 默认值,元素不浮动,遵循标准流的排列规则
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.box{
float:left;
background-color: aqua;
width: 300px;
height: 300px;
margin: 0 auto;
}
.clear{
clear:both;
height: 0; /* 隐藏空元素,不占用额外空间 */
overflow: hidden;
}
</style>
</head>
<body>
<div>
<div class="box">浮动</div>
<div class="clear"></div>
</div>
</body>
</html>

7.复合选择器与伪类

复合选择器

选择器类型 语法符号 核心规则 适用场景
后代选择器 空格 匹配所有后代元素(父子 / 祖孙) 深层嵌套元素的样式设置
子选择器 大于号 > 仅匹配直接子元素(父子) 精准匹配直接嵌套元素,避免深层影响
并集选择器 逗号 , 批量匹配多个选择器,设置相同样式 多个元素共享样式,减少代码冗余
交集选择器 无分隔符 匹配同时满足所有选择器条件的元素 精准定位特定标签 + 特定类 / ID 的元素
相邻兄弟选择器 加号 + 匹配紧接在后的同级元素 相邻同级元素的差异化样式(如表单标签 + 输入框)
属性选择器 E[attr] 匹配所有拥有 attr 属性的 E 元素(不关心属性值) input[disabled](匹配所有禁用的输入框)

(1)后代选择器

1
2
3
4
5
6
/*父  子	  此时只要是div子类是span标签的都会进行生效!!!!! */
div span{
width: 100px;
height: 100px;
background-color: yellow;
}

(2)子选择器

1
2
3
4
 /* 父 子   只会生效div父容器最近的子容器p,只会生效一个!!!!*/
div > p{
color:aquamarine;
}

(3)并集选择器

1
2
3
4
/*标签名1,标签名2,标签名3  只要是该标签都会生效此样式   */
div,p,img{
backgourd-color: yellow;
}

(4)交集选择器

1
2
3
4
/* 标签名.类名	只有标签名是p并且类名为acc的才生效此样式 */
p.acc{
color: yellow;
}

(5)相连兄弟选择器

1
2
3
4
5
6
7
8
9
/* 此时div统计别的p标签生效此样式,只会生效最近的一个!!!! */
div + p{
color:yellow;
}

<div>大兄弟</div>
<p>兄弟1</p>
<p>兄弟2</p>
<div>兄弟3</div>

(6)属性选择器

1
2
3
4
5
[love]{
color:red;
}

<div love></div> 这个div含有love属性,会选择这个

(7)选择器三大特性

继承性:
子级默认继承父级文字控制属性。如:body

层叠性:
相同的属性会覆盖,后面的覆盖前面的
不同的属性会叠加,不同的css属性都生效
如:div{color = red;font-size = 30px;} div{color = green;font-wigth = 600}


此时div会生效 后面的颜色 ,font-size 和 font-wigth 都会生效

优先级:
通配符选择器 < 标签选择器 < 类选择器 < id选择器 < 行内选择器 < !important
!important 放到 style样式里面; 如: color = red !important;

伪类

(1)状态伪类

类别 伪类 描述 典型应用元素
链接状态 :link 未访问的链接 <a>
:visited 已访问的链接 <a>
用户交互 :hover 鼠标悬停 所有可见元素
:active 激活/点击瞬间 所有可交互元素
:focus 获得焦点 表单元素、链接
输入状态 :checked 被选中 <input type="checkbox/radio">
:enabled 可用状态 表单元素
:disabled 禁用状态 表单元素
:required 必填字段 <input>, <select>
:optional 可选字段 <input>, <select>
:valid 验证通过 有验证的表单元素
:invalid 验证失败 有验证的表单元素
:in-range 数值在范围内 <input type="number/range">
:out-of-range 数值超出范围 <input type="number/range">
:read-only 只读状态 表单元素
:read-write 可读写状态 表单元素
:placeholder-shown 显示占位符 <input>, <textarea>
结构状态 :target URL片段标识目标 任何有id的元素
:playing 媒体正在播放 <audio>, <video>
:paused 媒体暂停 <audio>, <video>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>伪类语法</title>
<style>
a:hover{
color: aqua;
text-decoration:none;
font-size:80px;
font-weight:100px ;
cursor:pointer;/*wait 等待;help 可用的帮助;text 表示文本; crosshair 呈十字状;
/*点击超链接弹出样式*/
}
/* a:link{
color:blueviolet;
/*点击不放变此类型格式*/

/* a:visited{
color: chocolate;
/*点过超链接一次后变此格式 告诉你已看过*/
</style>
</head>
<body>
<a href="./img/32559.jpg">快来点我</a>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
<style>
/* 选中状态 */
input:checked + label { color: green; font-weight: bold; }

/* 禁用状态 */
input:disabled { background: #f0f0f0; cursor: not-allowed; }

/* 必填字段 */
input:required { border-left: 3px solid red; }

/* 验证状态 */
input:valid { border-color: green; }
input:invalid { border-color: red; }

/* 显示占位符时 */
input:placeholder-shown { font-style: italic; color: #999; }

/* 范围验证 */
input[type="number"]:in-range { background: #e6ffe6; }
input[type="number"]:out-of-range { background: #ffe6e6; }

/* 不确定状态(部分选中) */
.checkbox-group:indeterminate + label { color: orange; }
</style>

<!-- 示例HTML -->
<input type="checkbox" id="agree" checked>
<label for="agree">我同意条款</label>

<input type="email" required placeholder="请输入邮箱">
<input type="number" min="0" max="100" value="120">

(2)结构伪类

类别 伪类 描述 匹配示例 (n从0开始)
子元素位置 :first-child 父元素的第一个子元素 第1个
:last-child 父元素的最后一个子元素 最后一个
:only-child 父元素唯一的子元素 唯一的
序号选择 :nth-child(n) 父元素的第n个子元素 第n个
:nth-last-child(n) 父元素的倒数第n个子元素 倒数第n个
:nth-of-type(n) 同级中第n个指定类型元素 同类型第n个
:nth-last-of-type(n) 同级中倒数第n个指定类型元素 同类型倒数第n个
类型过滤 :first-of-type 同级中第一个指定类型元素 同类型第一个
:last-of-type 同级中最后一个指定类型元素 同类型最后一个
:only-of-type 同级中唯一的指定类型元素 同类型唯一
空元素 :empty 没有子元素的元素(包括文本节点) 空元素
根元素 :root 文档的根元素(HTML文档中就是<html> <html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>结构伪类演示</title>
<style>
.container {
border: 2px solid #333;
padding: 15px;
margin: 20px;
font-family: Arial, sans-serif;
}

/* 演示所有结构伪类 */
.container > :first-child { color: red; font-weight: bold; }
.container > :last-child { color: blue; border: 2px solid blue; padding: 5px; }
.container > div { background: yellow; padding: 10px; }
.container > :nth-child(3) { background: lightgreen; }
.container > :nth-child(odd) { text-decoration: underline; } /* odd为奇数 even为偶数 */
.container > :nth-child(3n+1) { border-left: 3px solid orange; }
.container > :nth-last-child(2) { font-style: italic; }
.container > p:first-of-type { background: #e6f7ff; }
.container > span:first-of-type { background: #f0ffe6; }
.container > p:last-of-type { background: #fff0f6; }
.container > span:last-of-type { background: #f6ffed; }
.container > div:only-of-type { border: 2px dashed purple; }
.container > p:nth-of-type(2) { color: darkred; font-size: 1.2em; }
.container > span:nth-of-type(even) { text-transform: uppercase; }
.container > p:nth-last-of-type(2) { background: #fffbe6; }
.container > :empty {
height: 20px;
background: repeating-linear-gradient(45deg, #f0f0f0, #f0f0f0 10px, #e0e0e0 10px, #e0e0e0 20px);
border: 1px solid #ccc;
}
.container > :not(:first-child):not(:last-child) { padding: 5px; margin: 2px 0; }
</style>
</head>
<body>
<h2>结构伪类效果展示</h2>
<div class="container">
<p>第一个段落 (:first-child - 红色粗体)</p>
<span>第一个span (:first-of-type - 浅绿背景)</span>
<p>第二个段落 (:nth-child(3) - 浅绿背景, :nth-of-type(2) - 深红大字体)</p>
<div>唯一的div (:only-child在父级中, :only-of-type在此容器中 - 黄底紫虚线)</div>
<p>第三个段落 (:nth-last-of-type(2) - 米黄背景)</p>
<span>第二个span (:nth-of-type(even) - 大写)</span>
<p>第四个段落</p>
<p></p> <!-- 空元素 (:empty - 条纹背景) -->
<span>第三个span (:last-of-type - 浅绿边框, :nth-last-child(2) - 斜体)</span>
</div>

<h3>选择器效果说明:</h3>
<ul>
<li><strong>:first-child</strong> - 匹配父元素的第一个子元素(红字)</li>
<li><strong>:last-child</strong> - 匹配父元素的最后一个子元素(蓝框)</li>
<li><strong>:nth-child(n)</strong> - 匹配第n个子元素(第3个浅绿背景)</li>
<li><strong>:first-of-type</strong> - 匹配每种类型的第一个(段落浅蓝,span浅绿)</li>
<li><strong>:only-of-type</strong> - 匹配唯一类型的元素(div紫虚线)</li>
<li><strong>:empty</strong> - 匹配空元素(条纹背景)</li>
<li><strong>:nth-of-type()</strong> - 匹配同类型的第n个(第2个段落深红)</li>
</ul>
</body>
</html>

8.列表和表格样式

(1)列表

属性 值类型 描述 示例
list-style-type 关键词 列表标记类型 list-style-type: circle 圆心; list-style-type: none 隐藏;
list-style-position 关键词 标记位置 list-style-position: inside;
list-style-image URL 标记图像 list-style-image: url('bullet.png');
list-style 复合值 列表简写 list-style: circle inside;

(2)表格

属性 值类型 描述 示例
border-collapse 关键词 边框合并 border-collapse: collapse;
border-spacing 长度值 边框间距 border-spacing: 2px;
empty-cells 关键词 空单元格 empty-cells: hide;
table-layout 关键词 表格布局 table-layout: fixed 固定布局 auto 自动布局(默认);
caption-side 关键词 标题位置 caption-side: bottom top等;

9.视觉效果

属性 功能说明 常用值
opacity 透明度控制 0-1 (0.5=半透明)
visibility 显示/隐藏 visible, hidden
display 显示模式 none, block, inline, flex
clip-path 裁剪形状 circle(), polygon(), inset()
filter 滤镜效果 blur(), brightness(), contrast()
box-shadow 盒子阴影 水平偏移 垂直偏移 模糊半径 颜色
text-shadow 文字阴影 水平偏移 垂直偏移 模糊半径 颜色
background-blend-mode 背景混合模式 multiply, screen, overlay
mix-blend-mode 元素混合模式 multiply, screen, overlay
backdrop-filter 背景滤镜 blur(), grayscale()
mask-image 遮罩图像 url(), linear-gradient()

(1)filter

滤镜函数 语法 取值范围 默认值 效果描述 示例
blur() blur(radius) 0px ~ 无穷大 0px 高斯模糊 blur(5px)
brightness() brightness(percentage) 0% ~ 无穷大 100% 亮度调节 brightness(150%)
contrast() contrast(percentage) 0% ~ 无穷大 100% 对比度调节 contrast(200%)
drop-shadow() drop-shadow(offset-x offset-y blur-radius color) box-shadow - 投影效果 drop-shadow(2px 2px 5px black)
grayscale() grayscale(percentage) 0% ~ 100% 0% 灰度化 grayscale(100%)
hue-rotate() hue-rotate(angle) 0deg ~ 360deg 0deg 色相旋转 hue-rotate(90deg)
invert() invert(percentage) 0% ~ 100% 0% 颜色反相 invert(100%)
opacity() opacity(percentage) 0% ~ 100% 100% 透明度 opacity(50%)
saturate() saturate(percentage) 0% ~ 无穷大 100% 饱和度调节 saturate(200%)
sepia() sepia(percentage) 0% ~ 100% 0% 深褐色效果 sepia(100%)
url() url(svg-filter-url) SVG滤镜文件路径 - 自定义SVG滤镜 url('#myFilter')

(2)backdrop-filter

滤镜函数 语法 效果描述 毛玻璃示例
blur() blur(radius) 高斯模糊背景 backdrop-filter: blur(10px);
brightness() brightness(percentage) 调整背景亮度 backdrop-filter: brightness(150%);
contrast() contrast(percentage) 调整背景对比度 backdrop-filter: contrast(120%);
grayscale() grayscale(percentage) 背景灰度化 backdrop-filter: grayscale(100%);
hue-rotate() hue-rotate(angle) 旋转背景色相 backdrop-filter: hue-rotate(90deg);
invert() invert(percentage) 反相背景颜色 backdrop-filter: invert(100%);
opacity() opacity(percentage) 调整背景透明度 backdrop-filter: opacity(50%);
saturate() saturate(percentage) 调整背景饱和度 backdrop-filter: saturate(200%);
sepia() sepia(percentage) 背景深褐色效果 backdrop-filter: sepia(50%);
drop-shadow() drop-shadow(...) 背景投影效果 backdrop-filter: drop-shadow(2px 2px 5px black);
url() url(#svg-filter) SVG滤镜 backdrop-filter: url(#filter);
none 关键词 无滤镜效果 backdrop-filter: none;

10.定位操作

属性 值类型 描述 示例
position 关键词 定位类型 position: absolute;
top 长度/百分比 距参考系顶部的距离 top: 10px;
right 长度/百分比 距参考系右侧的距离 right: 20%;
bottom 长度/百分比 距参考系底部的距离 bottom: 0;
left 长度/百分比 距参考系左侧的距离 left: 50px;
z-index 整数 堆叠层级(越大越靠前) z-index: 100;
inset 长度/百分比 top/right/bottom/left简写 inset: 10px;

(1)position

定位类型 参考坐标系 是否脱离文档流 是否保留原位置 常用场景
相对定位 relative 自身原位置 微调位置,为绝对定位提供参考
绝对定位 absolute 最近定位祖先元素 弹出层、图标、自定义组件
固定定位 fixed 视口(viewport) 导航栏、悬浮按钮、广告
粘性定位 sticky 最近滚动容器 吸顶导航、表格标题
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin: 0%;
padding: 0%;
}
div h1{
width: 100px;
height: 100px;
background-color: brown;

}
#dog{
width: 100px;
height: 100px;
background-color: aquamarine;
/* position:fixed ; 固定定位 脱离标准流 以屏幕四个边框为原点*/
position: fixed;
top: 200px;/*离浏览器上面距离*/
left: 300px;/*离浏览器左边距离*/
}
#cay{
width: 100px;
height: 100px;
background-color: aquamarine;
/* position: relative 相对位置会随着屏幕滚动而不显示且占位置 以自身左上角为原点 */
position: relative;
}
#cat{
width: 100px;
height: 100px;
background-color: aquamarine;
/* position: absolute; 绝对位置 脱离标准流 距离以前一位标签为标准 没有则以浏览器左上角为标准*/
position: absolute;
/* z-index: ; 表示优先显示该盒子标签 */
}
/* 定位一般采用 子绝父相 */
</style>
</head>
<body>
<div>
<div id="dog">固定</div>
<div id="cay">相对定位</div>
<div id="cat">绝对定位</div>
<h1>1</h1>
<h1>2</h1>
<h1>3</h1>
<h1>4</h1>
<h1>5</h1>
<h1>6</h1>
<h1>7</h1>
<h1>8</h1>
<h1>9</h1>
<h1>10</h1>
<h1>11</h1>
<h1>12</h1>
<h1>13</h1>
<h1>14</h1>
<h1>5</h1>
</div>
</body>
</html>

(2)z-index

堆叠: 数字越大越靠前

1
2
3
p{
z-index: 199;
}

11.平面转换和3D转换

属性 描述 示例
transform 操作
transform-origin 位置值 变换原点(中心点) transform-origin: 50% 50%;
transform-style flat preserve-3d 3D变换保留
perspective 长度值 透视距离 perspective: 1000px;
perspective-origin 位置值 透视原点 perspective-origin: top left;
backface-visibility visible hidden 背面可见性

(1)transform

类别 函数 语法 效果描述 示例
2D位移 translate() translate(x, y) 2D平面移动 transform: translate(50px, 100px);
2D旋转 rotate() rotate(angle) 2D旋转 transform: rotate(45deg);
2D缩放 scale() scale(x, [y]) 2D缩放 transform: scale(1.5);
2D倾斜 skew() skew(x-angle, y-angle) 2D倾斜变形 transform: skew(20deg, 10deg);
2D矩阵 matrix() matrix(a,b,c,d,e,f) 2D矩阵变换 matrix(1,0,0,1,50,100)
3D位移 translate3d() translate3d(x, y, z) 3D空间移动 translate3d(50px, 0, 100px)
translateZ() translateZ(z) Z轴移动 translateZ(100px)
3D旋转 rotate3d() rotate3d(x, y, z, angle) 绕轴旋转 rotate3d(1,1,0,45deg)
3D缩放 scale3d() scale3d(x, y, z) 3D空间缩放 scale3d(1,1,2)
scaleZ() scaleZ(z) Z轴缩放 scaleZ(1.5)
透视 perspective() perspective(distance) 透视距离 perspective(500px)
3D矩阵 matrix3d() matrix3d(16个值) 3D矩阵变换 复杂3D变换

12.过渡样式和渐变样式

(1)过渡

属性 值类型 描述 示例
transition 简写 所有过渡属性简写 transition: all 时间 linear;

配合hover使用,用于简单动画,在多重转换要先平移或旋转

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
*{
margin:0;
padding:0;
}
.dh{
width: 200px;
height: 200px;
background-color: aqua;
margin:200px auto;
/* transition:要过度的属性 过度时间 过度运动曲线 延时; */
/* linear 曲线的意思 均匀速度; ease 慢快慢; ease-in 慢快; ease-out 快慢; ease-in-out 慢快慢 比ease更墨迹一点 贝塞尔曲线 cubic-bezier()*/
transition: all 2s linear;
}
/* 增加过度到另外一个动画的时间 过度加在谁上面 */

.dh:hover{
/* width: 300px;
height: 300px;
background-color: yellow; */
opacity: 0;
}
.box{
width: 97%;
height: 200px;
background-color: aqua;
margin:20px auto;
position: relative;
}
.as,
.b{
width: 70px;
height: 70px;
background-color: rgb(129, 127, 255);
text-align: center;
line-height: 70px;
color: white;
font-size: 12px;
margin-top: 20px;
position: absolute;
/* 必须输入否则不一定生效 */
top:0;
left:0;
}
.as{
transition: all 5s linear;
}
.b{
margin-top: 110px;
transition: all 5s ease;
}
.box:hover .as,
.box:hover .b{
left:95%;
}
</style>

</head>
<body>
<div class="dh"></div>
<div class="box">
<div class="as">
innest
</div>
<div class="b">
ease
</div>
</div>
</body>
</html>

(2)渐变

渐变类型 函数 描述 基本语法
线性渐变 linear-gradient() 沿直线方向渐变 linear-gradient(方向, color-stop1, color-stop2, ...)
径向渐变 radial-gradient() 从中心向外辐射渐变 radial-gradient(形状 size at position, color-stop1, ...)

线性渐变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* 方向 + 颜色 */
.simple-gradient {
background: linear-gradient(to right, red, blue);
}

/* 角度 + 颜色 */
.angled-gradient {
background: linear-gradient(45deg, red, blue);
}

/* 多个颜色点 */
.multi-color-gradient {
background: linear-gradient(to right, red, yellow, green, blue);
}

径向渐变

1
2
3
4
5
6
7
8
9
10
11
12
13
14
/* 最简单的径向渐变 */
.simple-radial {
background: radial-gradient(circle, red, blue);
}

/* 指定位置 */
.positioned-radial {
background: radial-gradient(circle at top left, red, blue);
}

/* 椭圆形渐变 */
.ellipse-radial {
background: radial-gradient(ellipse, red, yellow, green);
}

13.flex布局

属性 值类型 描述 示例
display 关键词 启用flex,写在父容器 display: flex; display: inline-flex;
flex-direction 关键词 主轴方向 flex-direction: row; flex-direction: column;
flex-wrap 关键词 换行方式 flex-wrap: wrap; flex-wrap: nowrap;
justify-content 关键词 主轴对齐 justify-content: center; justify-content: space-between;
align-items 关键词 交叉轴对齐 align-items: center; align-items: stretch;
align-content 关键词 多行对齐 align-content: space-around;
flex 复合值 弹性因子 flex: 1; flex: 0 0 200px;
order 整数值 排列顺序 order: 1;

(1)justify-content

对齐方式 效果图示 主轴方向 示例
flex-start 主轴起点对齐 项目靠左/上排列 row: 左对齐 column: 上对齐 justify-content: flex-start;
flex-end 主轴终点对齐 项目靠右/下排列 row: 右对齐 column: 下对齐 justify-content: flex-end;
center 主轴居中对齐 项目在中间集中 水平和垂直居中 justify-content: center;
space-between 两端对齐 首尾项目贴边,中间等距 项目间间距相等 justify-content: space-between;
space-around 环绕对齐 每个项目两侧等距 项目周围间距相等 justify-content: space-around;
space-evenly 均匀对齐 所有间隔相等 包括两端在内完全等距 justify-content: space-evenly;

(2)align-items

对齐方式 效果描述 适用场景
stretch (默认) 拉伸填充 项目拉伸以填满交叉轴高度 等高列、表单布局
flex-start 交叉轴起点对齐 项目靠顶部/左侧对齐 导航栏、顶部对齐内容
flex-end 交叉轴终点对齐 项目靠底部/右侧对齐 底部工具栏、脚注
center 交叉轴居中对齐 项目在交叉轴居中 垂直居中内容、卡片

(3)align-content

对齐方式 效果描述 适用条件
stretch (默认) 拉伸填充 多行项目拉伸填满交叉轴 多行布局,空间分配
flex-start 交叉轴起点对齐 所有行紧贴交叉轴起点 顶部对齐,紧凑布局
flex-end 交叉轴终点对齐 所有行紧贴交叉轴终点 底部对齐,底部加载
center 交叉轴居中对齐 所有行在交叉轴居中 垂直居中,对称布局
space-between 两端对齐 首尾行贴边,行间等距 行间分布,最大利用空间
space-around 环绕对齐 每行两侧等距,边缘半距 周围留白,平衡布局
space-evenly 均匀对齐 所有间隔完全相等 完全均匀,现代设计

(4)flex

写在子容器中,flex: 数字 数字越大占用父容器越大

(5)flex-wrap

属性值:wrap 换行,需要给子级盒子设置宽!!

14.grid布局

属性 值类型 描述 示例
display 关键词 启用grid display: grid; display: inline-grid;
grid-template-columns 尺寸值 列定义 grid-template-columns: 1fr 1fr 1fr;
grid-template-rows 尺寸值 行定义 grid-template-rows: 100px auto;
grid-template-areas 区域名 区域模板 grid-template-areas: "header header" "sidebar main";
grid-gap 长度值 网格间距 grid-gap: 20px;
grid-column-gap 长度值 列间距 grid-column-gap: 10px;
grid-row-gap 长度值 行间距 grid-row-gap: 15px;
grid-column 位置值 列位置 grid-column: 1 / 3;
grid-row 位置值 行位置 grid-row: 1;
grid-area 位置值 区域位置 grid-area: header;
justify-items 关键词 水平对齐 justify-items: center;
align-items 关键词 垂直对齐 align-items: start;
justify-content 关键词 网格对齐 justify-content: space-between;
align-content 关键词 垂直对齐 align-content: center;
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
1.容器父盒子设置: dispaly: grid;

2.设置子盒子每列数: grid-template-columns: 1fr 1fr 1fr 1fr; 这里写几个子盒子就有几个,自动填充,参数表示占用空间,可以为其他数字
设置子盒子每行数: grid-template-rows: 1fr 1fr 1fr 1fr 1fr; 这里写几个子盒子就有几个,自动填充

函数写法:如果需要每列或行需要分100个可以使用repeat函数: grid-template-columns: repeat(11,1fr) 分11列


3.设置子盒子行和列间距:
gap:10px; 每个盒子行和列各10px分离
gap:10px 20px; 每个盒子行为10px 列为20px
columm-gap:10px 列10px分离
rows-gap:20px 行20px分离


4.自动填充响应式:
使用repeat()函数、minmax()函数

grid-template-columns: repeat(auto-fill,minmax(最小值,1fr))
auto-fill 表示自适应子盒子数量; minmax() 表示子盒子宽度最小值,如果小于给定的值,自动换行到下一列,最大值为1fr


5.网格线:
可以实现元素跨行或跨列显示
grid-column: 开始线编号/结束线编号; 跨列
grid-row: 开始线编号/结束线编号; 跨行

如:要跨 2列2行:
grid-cloumn: 1 / 3; 或者: grid-cloumn: 1 / span 2;
grid-rows: 1 / 3; 或者: grid-rows: 1 / span 2;

分开其他写法:
grid-column-start: 开始线编号;
grid-column-end: 结束线编号;



6.网格填充方式
网格填充默认按行,如何修改为列???
grid-auto-flow: column; 按列排序,默认按行



7.图片缩放
object-fit: fill
参数:
fill 默认,不保持宽高比,可能导致内容变形; contain 保持内容宽高比,但是容器会有空白; cover 保持内容宽高比,容器无空白;

配合:
object-position: center/top/left/right 控制内容再容器内的对齐位置



8.控制元素对齐位置
如果我想让元素左对齐或右对齐等,如何实现???
justify-items: center/start/end/stretch 水平对齐 stretch 默认值; start 左对齐; end 右对齐;
algin-items: center/start/end/stretch 垂直对齐 stretch 默认值; start 顶部对齐;end 底部对齐;


注:如果元素有宽高,默认左顶对齐!!!!

15.动画

使用流程:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
div{
animation: start 2s linear infinite 动画名、时间必须写,其他不必
}

@keyframes start{ 这里写上动画名
0%{

}

10%{

}
...
100%{}
}
属性 值类型 描述 示例
animation 简写 所有动画属性的简写 animation: 动画名 时间 linear infinite(无限重复) alternate(返回动画);
animation-play-state 关键词 动画播放状态 animation-play-state: paused 暂停;

动画时间线

和动画搭配使用

属性 值类型 描述 浏览器支持
animation-timeline 时间线源 指定时间线来源 Chrome 85+, Firefox 118+
1
2
3
4
5
animation-timeline: 函数()  

函数:
scroll() 屏幕滚动执行动画,到最底面100%
view() 屏幕滚动到当前元素时,开始做动画

16.用户界面效果样式

属性 值类型 描述 示例
cursor 关键词 鼠标光标 cursor: pointer; cursor: not-allowed;
outline 复合值 轮廓线 outline: 2px solid blue;
resize 关键词 调整大小 resize: both; resize: none;
user-select 关键词 用户选择 user-select: none; user-select: all;
pointer-events 关键词 指针事件 pointer-events: none;
caret-color 颜色值 输入光标颜色 caret-color: red;
scroll-behavior 关键词 滚动行为 scroll-behavior: smooth;

(1)cursor

取值 外观效果 适用场景 兼容性
default 默认箭头指针(系统默认) 普通不可点击元素(文本、静态 div、图片等) 所有浏览器
pointer 标准手型(指尖指向元素) 可点击元素(按钮、链接、可点击卡片、图标) 所有现代浏览器 + IE6+
not-allowed 禁止图标(圆圈带斜杠) 禁用状态元素(禁用按钮、不可操作的输入框) 所有现代浏览器 + IE9+
text 文本选择指针(I 型光标) 可编辑文本(输入框、文本域、可选中的段落)
vertical-text 垂直文本选择指针(竖排 I 型) 竖排文本、垂直排版的可编辑内容
move 移动指针(十字箭头) 可整体拖拽移动的元素(弹窗、拖拽组件、布局模块)
crosshair 十字线指针(精准定位) 绘图工具、精准选择区域、截图工具
ns-resize 上下双向箭头(垂直调整) 可垂直调整大小的元素(文本域高度、弹窗上下边框)
ew-resize 左右双向箭头(水平调整) 可水平调整大小的元素(输入框宽度、弹窗左右边框)
nesw-resize 斜向双向箭头(右上 - 左下) 可斜向调整大小的元素(自定义弹窗、画布元素)
nwse-resize 斜向双向箭头(左上 - 右下) 可斜向调整大小的元素(自定义弹窗、画布元素)
help 帮助指针(箭头带问号 / 感叹号) 帮助提示、说明文档链接、悬停可查看详情的元素
wait 等待指针(加载转圈 / 沙漏) 页面加载、数据请求、耗时操作(如文件上传)
progress 进度指针(加载 + 箭头并存) 后台执行耗时操作,但仍可交互的场景(区别于 wait 的不可交互)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>CSS cursor 所有取值表格汇总</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
font-family: "Microsoft Yahei", sans-serif;
}

.container {
width: 90%;
max-width: 1000px;
margin: 30px auto;
}

/* 表格核心样式 */
.cursor-table {
width: 100%;
border-collapse: collapse;
table-layout: fixed;
text-align: left;
border-radius: 8px;
overflow: hidden;
box-shadow: 0 2px 6px rgba(0, 0, 0, 0.1);
}

/* 表头样式 */
.cursor-table th {
background-color: #0066cc;
color: #fff;
font-weight: 500;
padding: 14px 16px;
border: 1px solid #004499;
}

/* 单元格样式 */
.cursor-table td {
padding: 12px 16px;
border: 1px solid #eee;
color: #333;
font-size: 14px;
word-wrap: break-word;
}

/* 奇偶行变色,提升可读性 */
.cursor-table tbody tr:nth-child(even) {
background-color: #f0f7ff;
}

/* 光标演示单元格:放大交互区域,提示效果更明显 */
.cursor-demo {
background-color: #f5f5f5;
border-radius: 4px;
padding: 8px 12px;
display: inline-block;
font-family: "Consolas", monospace;
color: #dc3545;
}

/* 应用不同 cursor 样式到演示单元格 */
.cursor-default { cursor: default; }
.cursor-pointer { cursor: pointer; }
.cursor-hand { cursor: hand; }
.cursor-not-allowed { cursor: not-allowed; }
.cursor-text { cursor: text; }
.cursor-vertical-text { cursor: vertical-text; }
.cursor-move { cursor: move; }
.cursor-crosshair { cursor: crosshair; }
.cursor-ns-resize { cursor: ns-resize; }
.cursor-ew-resize { cursor: ew-resize; }
.cursor-nesw-resize { cursor: nesw-resize; }
.cursor-nwse-resize { cursor: nwse-resize; }
.cursor-help { cursor: help; }
.cursor-wait { cursor: wait; }
.cursor-progress { cursor: progress; }

/* 表格标题 */
.cursor-table caption {
font-size: 18px;
color: #222;
margin-bottom: 10px;
font-weight: bold;
}
</style>
</head>
<body>
<div class="container">
<table class="cursor-table">
<caption>CSS cursor 所有取值完整汇总</caption>
<thead>
<tr>
<th>分类</th>
<th>取值名称</th>
<th>光标演示(悬浮查看效果)</th>
<th>适用场景</th>
</tr>
</thead>
<tbody>
<!-- 基础交互类 -->
<tr>
<td rowspan="4">基础交互类</td>
<td>default</td>
<td><span class="cursor-demo cursor-default">cursor: default;</span></td>
<td>普通不可点击元素(静态文本、静态图片、普通div)</td>
</tr>
<tr>
<td>pointer</td>
<td><span class="cursor-demo cursor-pointer">cursor: pointer;</span></td>
<td>可点击元素(按钮、链接、可点击卡片、图标、下拉菜单)</td>
</tr>
<tr>
<td>hand</td>
<td><span class="cursor-demo cursor-hand">cursor: hand;</span></td>
<td>兼容极低版本 IE(IE6/7/8),现代浏览器已废弃,优先使用 pointer</td>
</tr>
<tr>
<td>not-allowed</td>
<td><span class="cursor-demo cursor-not-allowed">cursor: not-allowed;</span></td>
<td>禁用状态元素(禁用按钮、不可编辑输入框、无效操作项)</td>
</tr>

<!-- 文本操作类 -->
<tr>
<td rowspan="2">文本操作类</td>
<td>text</td>
<td><span class="cursor-demo cursor-text">cursor: text;</span></td>
<td>可编辑/可选中文本(输入框、文本域、可复制段落)</td>
</tr>
<tr>
<td>vertical-text</td>
<td><span class="cursor-demo cursor-vertical-text">cursor: vertical-text;</span></td>
<td>竖排文本、垂直排版的可编辑/可选中内容</td>
</tr>

<!-- 布局操作类 -->
<tr>
<td rowspan="6">布局操作类</td>
<td>move</td>
<td><span class="cursor-demo cursor-move">cursor: move;</span></td>
<td>可整体拖拽移动的元素(弹窗、拖拽组件、布局模块、卡片)</td>
</tr>
<tr>
<td>crosshair</td>
<td><span class="cursor-demo cursor-crosshair">cursor: crosshair;</span></td>
<td>绘图工具、精准选择区域、截图工具、颜色拾取器</td>
</tr>
<tr>
<td>ns-resize</td>
<td><span class="cursor-demo cursor-ns-resize">cursor: ns-resize;</span></td>
<td>可垂直调整大小的元素(文本域高度、弹窗上下边框、表格行高)</td>
</tr>
<tr>
<td>ew-resize</td>
<td><span class="cursor-demo cursor-ew-resize">cursor: ew-resize;</span></td>
<td>可水平调整大小的元素(输入框宽度、弹窗左右边框、表格列宽)</td>
</tr>
<tr>
<td>nesw-resize</td>
<td><span class="cursor-demo cursor-nesw-resize">cursor: nesw-resize;</span></td>
<td>可斜向(右上-左下)调整大小的元素(自定义弹窗、画布元素)</td>
</tr>
<tr>
<td>nwse-resize</td>
<td><span class="cursor-demo cursor-nwse-resize">cursor: nwse-resize;</span></td>
<td>可斜向(左上-右下)调整大小的元素(自定义弹窗、画布元素)</td>
</tr>

<!-- 辅助提示类 -->
<tr>
<td rowspan="3">辅助提示类</td>
<td>help</td>
<td><span class="cursor-demo cursor-help">cursor: help;</span></td>
<td>帮助提示、说明文档链接、悬停可查看详情的图标/文字</td>
</tr>
<tr>
<td>wait</td>
<td><span class="cursor-demo cursor-wait">cursor: wait;</span></td>
<td>页面加载、数据请求、文件上传等耗时操作(不可交互)</td>
</tr>
<tr>
<td>progress</td>
<td><span class="cursor-demo cursor-progress">cursor: progress;</span></td>
<td>后台执行耗时操作,但页面仍可交互(区别于 wait 的不可交互)</td>
</tr>
</tbody>
</table>
</div>
</body>
</html>

(2)outline

文字边框,表单边框

属性名 作用说明 常用取值示例
outline-width 设置轮廓线宽度 1px2pxthin(细)、thick(粗)
outline-style 设置轮廓线样式(必填,无默认值,不设置则无轮廓) solid(实线)、dashed(虚线)、dotted(点线)、none(无轮廓)
outline-color 设置轮廓线颜色 #0066ccrgba(0,102,204,0.5)currentColor(继承元素文本色)
outline-offset 设置轮廓线与元素边框 / 边缘的间距(可选,默认 0) 2px5px(正值向外偏移,负值向内偏移)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>极简 outline 效果</title>
<style>
/* 核心元素:同时展示 border 和 outline */
.outline-demo {
width: 200px;
height: 100px;
margin: 50px auto;
padding: 10px;
border: 2px solid #dc3545; /* 红色边框(占用布局) */
outline: 2px solid #0066cc; /* 蓝色轮廓(不占用布局) */
outline-offset: 5px; /* 轮廓与边框间距,更直观 */
border-radius: 8px; /* 验证 outline 不跟随圆角 */
}

/* 输入框聚焦 outline 高亮(常用实战效果) */
.input-outline {
display: block;
width: 200px;
margin: 20px auto;
padding: 10px;
border: 1px solid #eee;
border-radius: 4px;
}

.input-outline:focus {
outline: 2px solid rgba(0, 102, 204, 0.4); /* 聚焦淡蓝轮廓 */
outline-offset: 2px;
}
</style>
</head>
<body>
<!-- outline 与 border 对比演示 -->
<div class="outline-demo">红色 border + 蓝色 outline</div>

<!-- 输入框聚焦 outline 演示 -->
<input class="input-outline" placeholder="点击聚焦看 outline">
</body>
</html>

(3)resize

可拖拽文本框,需要和overflow配合使用

1
2
3
4
selector {
resize: 取值;
overflow: auto; /* 必备:resize 仅对 overflow 非 visible 的元素生效 */
}
取值 效果说明
none 禁止用户调整元素尺寸(默认值)
both 允许用户同时调整元素的宽度和高度
horizontal 仅允许用户调整元素的宽度
vertical 仅允许用户调整元素的高度
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>极简 resize 效果</title>
<style>
/* 核心 resize 演示元素 */
.resize-demo {
width: 200px;
height: 150px;
margin: 50px auto;
padding: 10px;
border: 1px solid #0066cc;
border-radius: 8px;
overflow: auto; /* 必备:启用 resize 的前提 */
resize: both; /* 允许同时调整宽高(核心属性) */
}

/* 仅调整高度的示例 */
.resize-vertical {
width: 200px;
height: 100px;
margin: 20px auto;
padding: 10px;
border: 1px solid #dc3545;
border-radius: 8px;
overflow: auto;
resize: vertical; /* 仅允许调整高度 */
}
</style>
</head>
<body>
<div class="resize-demo">
可同时调整宽高<br>
拖动右下角的调整手柄即可
</div>

<div class="resize-vertical">
仅可调整高度<br>
拖动底部的调整手柄即可
</div>
</body>
</html>

(4)user-select

用户文本选中

取值 效果说明 兼容性
auto 默认值,浏览器自动决定是否可选中(大部分元素可选中) 所有浏览器(需加前缀兼容旧版)
none 禁止用户选中元素及其子元素的内容 所有浏览器(需加前缀兼容旧版)
text 仅允许用户选中文本内容,不包含元素本身 所有浏览器(需加前缀兼容旧版)
all 点击一次即可选中元素内所有内容(无需拖拽) 现代浏览器支持
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>极简 user-select 效果</title>
<style>
/* 统一兼容前缀 */
.user-select-demo {
width: 90%;
max-width: 500px;
margin: 30px auto;
padding: 15px;
border-radius: 8px;
margin-bottom: 20px;
}

/* 禁止选中 */
.select-none {
background-color: #f0f7ff;
/* 核心样式 + 兼容前缀 */
user-select: none;
-webkit-user-select: none;
-moz-user-select: none;
-ms-user-select: none;
}

/* 仅可选中文字 */
.select-text {
background-color: #f5f5f5;
user-select: text;
-webkit-user-select: text;
}

/* 点击全选 */
.select-all {
background-color: #f0fcfb;
user-select: all;
-webkit-user-select: all;
}
</style>
</head>
<body>
<div class="user-select-demo select-none">
🔴 禁止选中:尝试拖拽选中我,无法生效(常用于按钮、导航、图标等可交互元素)
</div>

<div class="user-select-demo select-text">
🟢 仅可选中文本:可以拖拽选中这段文字(常用于普通文本、文章内容)
</div>

<div class="user-select-demo select-all">
🟡 点击全选:点击任意位置即可选中所有内容(常用于代码块、复制文本)
</div>
</body>
</html>

(4)caret-color

改变光标颜色

取值类型 具体示例 说明
具体颜色值 #0066ccrgb(0, 102, 204)rgba(0,102,204,0.8) 自定义光标颜色,与页面配色保持一致
关键字 auto(默认值)、transparent(透明) auto 继承元素文本颜色或浏览器默认色;transparent 隐藏光标
系统颜色关键字 currentColor(继承元素当前文本颜色) 跟随元素 color 属性变化,保持样式统一

三、css3变量与函数

1.变量

(1)变量定义

变量必须以为开头,可在任意选择器内声明,遵循「CSS 继承规则」,全局变量建议声明在 :root 伪类(对应 HTML 根元素,作用域全局);

(2)使用变量(调用)

通过 var() 函数调用已声明的变量,可传入第二个参数作为「默认值」(当变量未定义时生效)。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
/* 全局变量(:root 内声明,全局生效) */
:root {
--main-color: #0066cc; /* 主色调 */
--font-size-base: 14px; /* 基础字体大小 */
--container-width: 800px; /* 容器宽度 */
--box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1); /* 复合阴影值 */
}

/* 局部变量(仅在 .card 内生效,可覆盖全局变量) */
.card {
--card-bg: #fff; /* 卡片背景色(局部变量) */
--main-color: #dc3545; /* 覆盖全局主色调(仅.card内生效) */
}


/*使用变量 */
/* 调用全局变量 */
.container {
width: var(--container-width);
margin: 0 auto;
font-size: var(--font-size-base);
}

.btn {
background-color: var(--main-color);
color: #fff;
box-shadow: var(--box-shadow);
}

/* 调用局部变量 + 默认值(若 --card-padding 未定义,使用 20px) */
.card {
background-color: var(--card-bg);
padding: var(--card-padding, 20px); /* 第二个参数为默认值 */
}

2.函数

功能分类 函数名称 基本语法 核心用途 实用代码示例
变量相关 var() var(--变量名, 默认值) 调用已声明的 CSS 变量,默认值在变量未定义时生效 background-color: var(--main-color, #0066cc);
颜色处理 rgb() rgb(红, 绿, 蓝)(取值 0-255) 设置不透明 RGB 颜色,替代十六进制颜色,更易理解 color: rgb(0, 102, 204);
颜色处理 rgba() rgba(红, 绿, 蓝, 透明度)(透明度 0-1) 设置带透明度的 RGB 颜色,实现半透明效果,无需额外设置 opacity background: rgba(0, 102, 204, 0.5);
颜色处理 hsl() hsl(色相, 饱和度, 亮度)(饱和度 / 亮度 0%-100%) 按色相、饱和度、亮度设置颜色,更易调整同色系配色(如浅深变体) color: hsl(210, 100%, 40%);
颜色处理 hsla() hsla(色相, 饱和度, 亮度, 透明度) 带透明度的 HSL 颜色,兼顾色系统一和半透明需求 background: hsla(210, 100%, 40%, 0.5);
颜色处理 opacity() opacity(颜色值, 透明度) 基于已有颜色调整透明度,无需重新定义 RGB/HSL 值,保持配色一致性 background: opacity(var(--main-color), 0.8);
尺寸计算 calc() calc(运算表达式)(运算符前后加空格) 动态计算 CSS 尺寸,支持混合单位(px/%/vw/rem),解决自适应布局问题 width: calc(100% - 40px);min-height: calc(100vh - 60px);
自适应布局 min() min(值1, 值2, ...) 取多个值中的最小值,实现「最大不超过某值」的自适应布局,无需媒体查询 width: min(800px, 90vw);(最大 800px,最小 90% 视口宽度)
自适应布局 max() max(值1, 值2, ...) 取多个值中的最大值,实现「最小不低于某值」的自适应布局,无需媒体查询 height: max(40px, 5vh);(最小 40px,最大 5% 视口高度)
自适应布局 clamp() clamp(最小值, 中间值, 最大值) 限制值在区间内,中间值自适应屏幕,实现「小屏取最小、大屏取最大、中屏自适应」 font-size: clamp(14px, 5vw, 24px);width: clamp(300px, 80vw, 800px);
资源引入 url() url(资源路径/链接) 引入外部资源,如背景图片、图标、字体文件等 background-image: url("bg.jpg");src: url("font.ttf");
文本 / 属性关联 attr() attr(HTML属性名) 获取元素的 HTML 属性值,动态插入到样式中(常用于伪元素内容) content: attr(data-title);(获取元素 data-title 属性值)
背景裁剪 linear-gradient() linear-gradient(方向, 颜色1, 颜色2, ...) 创建线性渐变背景,替代静态背景图,实现丰富的视觉效果 background: linear-gradient(to right, #0066cc, #28a745);
背景裁剪 radial-gradient() radial-gradient(形状, 颜色1, 颜色2, ...) 创建径向渐变背景,从中心向外扩散的颜色过渡 background: radial-gradient(circle, #0066cc, #28a745);

四、css3布局单位和值类型

单位分类 单位符号 核心说明 实用场景 代码示例
绝对单位(固定尺寸) px 像素(屏幕物理像素的抽象),尺寸固定,不随其他元素 / 屏幕变化 固定尺寸的组件、按钮、边框、文字大小(基础排版) width: 200px;border: 1px solid #eee;
pt 磅(印刷单位,1pt=1/72 英寸),适用于打印场景 打印样式中的文本、容器尺寸(保证纸质文档规整) font-size: 12pt;(打印文档正文)
cm/mm 厘米 / 毫米(物理长度单位),精准对应现实尺寸 打印报表、合同等需要精准物理尺寸的场景 @page { margin: 2cm; }(打印页面边距)
相对单位(随参考元素变化) em 相对于父元素的字体大小(继承父元素 font-size),存在嵌套叠加效应 基于父元素的排版、组件内间距、自适应文字 padding: 1.5em;font-size: 1.2em;
rem 相对于根元素(:root)的字体大小,无嵌套叠加,全局统一参考 全局自适应布局、响应式文字、组件尺寸(现代开发首选) width: 15rem;font-size: 1.1rem;
% 相对于父元素的对应属性值(宽 / 高对应父元素宽 / 高,间距对应父元素宽) 流式布局、自适应容器、百分比宽高设置 width: 100%;margin: 5% 0;
ch 相对于数字 “0” 的宽度,等宽排版更精准 代码块、表单输入框、等宽文本对齐 width: 30ch;(输入框最多容纳 30 个等宽字符)
视口单位(随视口窗口变化) vw 视口宽度的 1%(1vw = 视口宽度 / 100) 自适应全屏宽度、响应式容器、无需媒体查询 width: 90vw;(容器占视口 90% 宽度)
vh 视口高度的 1%(1vh = 视口高度 / 100) 全屏布局、页面主体高度、垂直自适应 min-height: 100vh;(页面占满整个视口高度)
vmin 取 vw 和 vh 中的最小值,适配横竖屏切换 横竖屏兼容的弹窗、居中组件(避免溢出) width: 80vmin;(弹窗在横竖屏均不超出视口)
vmax 取 vw 和 vh 中的最大值,优先利用大屏空间 大屏展示的图片、横幅,充分利用视口空间 height: 50vmax;(横幅在大屏上更高)
值类型名称 核心说明 适用属性 代码示例
关键字值 CSS 预定义的关键字,语义化明确 布局、显示、颜色等大部分属性 display: block;position: fixed;color: red;
数值型(带单位) 数字 + 布局单位(如上所述),定义具体尺寸 宽高、间距、边框、字体大小等 height: 40px;margin: 1rem;font-size: 14px;
数值型(无单位) 纯数字,无附加单位,通常表示比例 / 透明度等 opacityline-heightflex-grow opacity: 0.8;line-height: 1.8;flex-grow: 1;
颜色值 表示颜色的各类格式,包括关键字、十六进制、RGB 等 所有与颜色相关的属性(background、color 等) #0066ccrgb(0,102,204)rgba(0,102,204,0.5)hsl(210,100%,40%)
字符串值 用引号(单 / 双)包裹的文本内容,语义化描述 content(伪元素)、font-family content: "提示文本";font-family: "Microsoft Yahei", sans-serif;
布尔值 true/false 或 CSS 等效关键字(如 normal/none 部分交互、布局属性(如 user-sele

五、javascript

1.js介绍

赋予页面「灵魂」和「行为」(比如点击按钮弹出提示、输入框验证内容、轮播图自动切换),让静态页面变「活」。

javascript文件后缀为 .js

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script>
//1.js可以放到head标签里面
...
</script>
</head>
<body>
<!-- 2.内部嵌套 -->
<button onclick="alert('黄色')">点击我</button>

<script>
//放到body里面
</script>
</body>
</html>

2.基本输入输出语法

语法1:document.write(输入内容) 将会显示在浏览器页面

语法2:alert(输入内容) 会像一个弹窗弹出来

语法3:console.log(控制台打印) 在控制台显示内容

语法4:prompt(输入内容) 会在浏览器上面弹出输入框 输入语句 +prompt() 转为数字类型

语法5:confirm(输入内容) 弹出确定框

语法6:console.dir(输入元素) 显示元素内容数据

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>初识js</title>
<script>
alert("我要变强"); //1.弹窗内容

document.write("哈哈");// 2.内容将会打印在页面上 内容里也可以加入html元素
document.write('<h1>我要变大</h1>');//加入h1标,会识别html样式

//3.控制台输出 在游览器检查中的控制台查看输出的内容 用于调试内容 console.log
console.log("哈哈哈,初识控制台");

//4.接收游览器弹框输入 prompt
var name = prompt("你叫啥名字");//name 个它一个变量名用于输出用户输入的内容
console.log(name);
</script>
<script>
alert("第二个脚本");
confirm("点击");
</script>
</head>
<body>
</body>
</html>

3.数据类型

(1)声明数据类型

关键字 可重新赋值 可重复声明 作用域 声明要求 推荐度
const ❌(引用不可变,引用类型内容可改) 块级 声明时必须赋值 🌟🌟🌟🌟🌟(首选,优先声明常量)
let 块级 可先声明后赋值 🌟🌟🌟🌟🌟(次选,声明需修改的变量)
var 函数级 无强制要求 ❌(不推荐,存在变量提升等缺陷)

(2)基本数据类型

数据类型类别 具体类型名称 核心说明 语法示例(可直接运行) 关键注意点(避坑指南)
基本数据类型(6 种,栈存储,值拷贝) 字符串(String) 表示文本内容,支持单 / 双 / 反引号包裹,反引号支持多行和变量插值 let str1 = "Hello JS"; let str2 = 10+20=${10+20}; 1. 单 / 双引号嵌套需内外不同 2. 反引号为 ES6 特性,支持换行 3. 值不可变(修改本质是创建新值)
数字(Number) 表示整数、小数(浮点数),统一无类型区分,包含特殊值 Infinity/NaN let num1 = 20; let num2 = 3.14; let num3 = 1/0;(Infinity) 1. NaN 不等于自身,判断用 isNaN() 2. 浮点数运算有精度误差 3. 支持正负无穷大(-Infinity
布尔值(Boolean) 表示逻辑真假,仅两个固定值:true(真)、false(假),用于条件判断 let isOk = true; let isGreater = 10 > 5;(返回 true 1. 非布尔值可隐式转换(0/""/null 转为 false) 2. 仅两个有效值,无其他扩展值
未定义(Undefined) 变量声明但未赋值时的默认值,标识「值不存在」,不推荐主动赋值 let a;(a 默认为 undefinedlet b = undefined;(不推荐) 1. 声明未赋值自动为 undefined 2. 避免主动赋值,空值优先用 null
空值(Null) 主动声明的「空引用」,标识变量无有效内容,专门用于初始化对象类型变量 let obj = null;(表示暂不指向任何对象) 1. 必须主动赋值才会出现 2. typeof null 返回 "object"(JS 历史遗留 Bug) 3. 表示「空对象引用」,与 undefined 语义不同
符号(Symbol)(ES6 新增) 表示唯一、不可重复的值,用于解决命名冲突,主要用于对象属性标识 let s1 = Symbol("name"); let s2 = Symbol("name"); console.log(s1===s2);false 1. 不支持 new 关键字,直接创建 2. 描述相同值也唯一 3. 入门阶段使用较少,高级开发场景用

(3)隐式转换和显式转换

显式转换:

转字符串:
转换方法 语法格式 核心说明 实操示例
String() 函数(全局) String(待转换值) 通用转换,支持所有数据类型,转换结果更规范 String(123) → "123"String(true) → "true"String(null) → "null"String(undefined) → "undefined"
toString() 方法(对象 / 基本类型实例) 待转换值.toString(进制)(进制可选,仅数字有效) 不支持 nullundefined,数字可指定进制转换 (123).toString() → "123"true.toString() → "true"(16).toString(2) → "10000"(转二进制)
拼接空字符串(简易方式) 待转换值 + "" 语法简洁,本质是隐式转换的简化,支持所有类型 123 + "" → "123"null + "" → "null"undefined + "" → "undefined"
转数字:
转换方法 语法格式 核心说明 实操示例
Number() 函数(全局) Number(待转换值) 通用转换,严格遵循数字规则,非数字内容转为 NaN Number("123") → 123Number("123a") → NaNNumber(true) → 1Number(false) → 0Number(null) → 0Number(undefined) → NaN
parseInt() 函数 parseInt(待转换值, 进制)(进制默认 10) 解析整数,从左往右提取数字,遇到非数字停止,不识别小数 parseInt("123.45") → 123parseInt("123a45") → 123parseInt("a123") → NaN
parseFloat() 函数 parseFloat(待转换值) 解析浮点数,从左往右提取数字,支持小数点,遇到非数字停止 parseFloat("123.45") → 123.45parseFloat("123.45a67") → 123.45parseFloat("a123.45") → NaN
一元 + 运算符(简易方式) + 待转换值 等价于 Number() 函数,语法简洁 +"123" → 123+true → 1+null → 0+"123a" → NaN
转bool:
转换方法 语法格式 核心说明 实操示例
Boolean() 函数(全局) Boolean(待转换值) 通用转换,明确区分「真值」和「假值」 真值转 true,假值转 false

(4)字符串常用方法

功能类别 方法名称 简洁语法 核心功能 实操示例(结果)
查询类 indexOf() str.indexOf(substr[, start]) 从左找子串,返回首次索引 /-1 "abcabc".indexOf("a") → 0"abcabc".indexOf("a",1) → 3
lastIndexOf() str.lastIndexOf(substr[, start]) 从右找子串,返回末次索引 /-1 "abcabc".lastIndexOf("a") → 3"abcabc".lastIndexOf("a",2) → 0
includes() str.includes(substr[, start]) 判断是否包含子串,返回布尔值 "hello js".includes("js") → true"hello js".includes("Java") → false
startsWith() str.startsWith(prefix[, start]) 判断是否以指定前缀开头,返回布尔值 "hello js".startsWith("hello") → true"hello js".startsWith("js") → false
endsWith() str.endsWith(suffix[, length]) 判断是否以指定后缀结尾,返回布尔值 "hello js".endsWith("js") → true"hello js".endsWith("llo",5) → true
截取类 slice() str.slice(start[, end]) 截取子串,支持负索引,不包含 end "hello js".slice(0,5) → "hello""hello js".slice(-2) → "js"
substring() str.substring(start[, end]) 截取子串,不支持负索引,自动交换首尾 "hello js".substring(0,5) → "hello""hello js".substring(5,0) → "hello"
修改 / 格式化类 toUpperCase() str.toUpperCase() 全部转为大写 "hello js".toUpperCase() → "HELLO JS"
toLowerCase() str.toLowerCase() 全部转为小写 "HELLO JS".toLowerCase() → "hello js"
trim() str.trim() 去除首尾空白字符 " hello js \t\n".trim() → "hello js"
replace() str.replace(old, new) 替换首次出现的子串,支持正则 "abcabc".replace("a", "x") → "xbcabc""abcabc".replace(/a/g, "x") → "xbcxbc"
replaceAll() str.replaceAll(old, new) 替换所有出现的子串,支持正则 "abcabc".replaceAll("a", "x") → "xbcxbc"
分割 / 拼接类 split() str.split(separator[, limit]) 以分隔符分割字符串,返回数组 "a,b,c".split(",") → ["a","b","c"]"a,b,c".split(",",2) → ["a","b"]
concat() str.concat(str1, str2...) 拼接多个字符串,返回新字符串 "hello".concat(" ", "js") → "hello js"
字符获取类 charAt() str.charAt(index) 获取指定索引的字符,越界返回空串 "hello js".charAt(0) → "h""hello js".charAt(100) → ""
at() str.at(index) 获取指定索引的字符,支持负索引,越界返回 undefined "hello js".at(-2) → "j""hello js".at(100) → undefined
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<script>
str = "hello"
str2 = "world"
str3 = " hhhh "
console.log(str.length);
console.log(str.charAt(1));
console.log(str.concat(",",str2));
document.write(str.concat(",",str2).slice(1,7))
document.write(str.substring(1,4))
console.log(str.substr(1,4));
console.log(str.indexOf("h"));
console.log(str3);
console.log(str3.trim());
console.log(str.padStart(10,"0"));
</script>
</body>
</html>

(5)数字常用方法

功能类别 方法名称 简洁语法 核心功能 实操示例(结果)
格式化为字符串 toString() num.toString([radix]) 转字符串,可选指定进制(2-36) (16).toString() → "16"(16).toString(2) → "10000"
四舍五入 / 精度处理 Math.round() Math.round(num) 四舍五入保留整数 Math.round(3.14) → 3Math.round(3.56) → 4
Math.ceil() Math.ceil(num) 向上取整,返回最小整数 Math.ceil(3.14) → 4Math.ceil(-3.14) → -3
Math.floor() Math.floor(num) 向下取整,返回最大整数 Math.floor(3.99) → 3Math.floor(-3.14) → -4
toFixed() num.toFixed([digits]) 保留指定小数位(0-20),四舍五入返回字符串 3.14159.toFixed(2) → "3.14"3.toFixed(2) → "3.00"
数字判断 / 验证 Number.isInteger() Number.isInteger(num) 严格判断是否为整数(仅 Number 类型) Number.isInteger(123) → trueNumber.isInteger(123.45) → false
Number.isNaN() Number.isNaN(num) 严格判断是否为 NaN(仅 Number 类型) Number.isNaN(NaN) → trueNumber.isNaN("123") → false

4.运算符

1.算数运算符

运算符 描述 示例 结果
+ 加法 5 + 2 7
- 减法 5 - 2 3
* 乘法 5 * 2 10
/ 除法 5 / 2 2.5
% 取模(余数) 5 % 2 1
** 指数(幂) 5 ** 2 25
++ 自增 let x=5; x++; 6
-- 自减 let x=5; x--; 4

2.赋值运算符

运算符 示例 等价于
= x = 5 x = 5
+= x += 5 x = x + 5
-= x -= 5 x = x - 5
*= x *= 5 x = x * 5
/= x /= 5 x = x / 5
%= x %= 5 x = x % 5
**= x **= 5 x = x ** 5
&&= x &&= y x = x && y
` =`
??= x ??= y x = x ?? y

注: ?? 表示检查前面的变量是否为空,如果为空赋值为右边的~ 如: let a = null; console.log(a ??= “未知”)

3.比较运算符

运算符 描述 示例 结果
== 等于(会类型转换) 5 == '5' true
=== 严格等于 5 === '5' false
!= 不等于 5 != '5' false
!== 严格不等于 5 !== '5' true
> 大于 5 > 3 true
< 小于 5 < 3 false
>= 大于等于 5 >= 5 true
<= 小于等于 5 <= 3 false

4.逻辑运算符

运算符 描述 示例
&& 逻辑与 true && falsefalse
` `
! 逻辑非 !truefalse

5.三元运算符

变量名 == 条件 ? 满足条件 : 不满足条件; 如: let man = a == 13 ? “满足” : “不满足”

5.控制语句

(1) if语句

1
2
3
4
5
6
7
8
9
10
//和java一样
if(条件){

}else if(条件){

}...{

}else{

}

(2)switch语句

1
2
3
4
5
6
7
8
9
10
switch(值){
case 条件:
语句
break;
case 条件:
语句
break;
default:
默认语句
}

(3)for循环

1
2
3
4
5
6
for(初始化变量名; 循环条件; 更新变量值){

}

//如:
for(let i = 0; i < 10; i++){}

(4)for..in循环

1
2
3
4
5
for(变量名 in 迭代器){}

//如:
let str = "nnnn"
for(let i in str){console.log(i)} // i 获取的是下标 0,1,2,3

(5)for..of循环

1
2
3
4
5
for(变量名 of 迭代器){}

//如:
let str = "nnnn"
for(let i of str){console.log(i)} // i 获取的是值 n,n,n,n

(6)while循环

1
2
3
4
while(值或条件){
...
更新值语句
}

(7)do..while循环

1
2
3
4
5
//至少做一次
do{
...
更新值语句
}while(值或条件)

(8)控制循环语句

break 退出整个循环

continue 跳出一次循环,执行下一个循环

return 退出整个函数

6.数组

(1)创建数组

方法 语法 描述 示例 结果
字面量 [] 创建数组最常用方式 [1, 2, 3] [1, 2, 3]
Array() new Array() 构造函数 new Array(1, 2, 3) [1, 2, 3]
Array.of() Array.of() 解决构造函数歧义 Array.of(5) [5]
Array.from() Array.from() 从类数组创建 Array.from('abc') ['a','b','c']
扩展运算符 [...] 从可迭代对象创建 [...'hello'] ['h','e','l','l','o']
1
2
3
4
5
6
let arr = [12,3,4,45,23]		// []创建
let arr2 = new Array(1,2,3,4,5) //Array对象创建
let arr3 = Array.of(1,2,3,4,5) //Array.of创建
let arr4 = Array.form("asdydd") //迭代器创建
let str = "sdgfff"
let arr5 = [...str] //迭代器创建

(2)增加和删除元素(改变原数组)

方法 描述 返回值 时间复杂度 示例 结果
push() 末尾添加元素 新长度 O(1) [1,2].push(3) [1,2,3]
pop() 末尾删除元素 删除的元素 O(1) [1,2,3].pop() [1,2]
unshift() 开头添加元素 新长度 O(n) [1,2].unshift(0) [0,1,2]
shift() 开头删除元素 删除的元素 O(n) [1,2,3].shift() [2,3]
splice() 任意位置增删 删除的元素数组 O(n) [1,2,3].splice(1,1,'a') [1,'a',3]

(3)数组操作

方法 描述 返回值 示例 结果
concat() 合并数组 新数组 [1,2].concat([3,4]) [1,2,3,4]
slice() 提取子数组 新数组 [1,2,3,4].slice(1,3) [2,3]
join() 数组转字符串 字符串 ['a','b'].join('-') 'a-b'
toString() 转为字符串 字符串 [1,2,3].toString() '1,2,3'
toReversed() 反转数组副本 新数组 [1,2,3].toReversed() [3,2,1]
toSorted() 排序数组副本 新数组 [3,1,2].toSorted() [1,2,3]
sort() 排序数组 [3,1,2].sort() [1,2,3]
reverse() 反转数组 [1,2,3].reverse() [3,2,1]
fill() 填充数组 new Array(3).fill(0) [0,0,0]
copyWithin() 复制内部元素 [1,2,3,4].copyWithin(0,2) [3,4,3,4]

(4)查找数组元素

方法 描述 返回值 是否严格相等 示例
find() 找第一个满足条件的元素 元素或undefined 自定义 [1,2,3].find(x=>x>1)2
findIndex() 找第一个满足条件的索引 索引或-1 自定义 [1,2,3].findIndex(x=>x>1)1
findLast() 找最后一个满足条件的元素 元素或undefined 自定义 [1,2,3,2].findLast(x=>x>1)2
findLastIndex() 找最后一个满足条件的索引 索引或-1 自定义 [1,2,3,2].findLastIndex(x=>x>1)3
indexOf() 找第一个匹配值的索引 索引或-1 === [1,2,2].indexOf(2)1
lastIndexOf() 找最后一个匹配值的索引 索引或-1 === [1,2,2].lastIndexOf(2)2
includes() 检查是否包含值 true/false === [1,2,3].includes(2)true
at() 获取指定位置元素 [1,2,3].at(-1) 3

(5)数组高级操作

方法 描述 是否中断 返回值 示例
forEach() 遍历每个元素 undefined arr.forEach(v => console.log(v))
map() 映射新数组 新数组 [1,2].map(x => x*2)[2,4]
filter() 过滤数组 新数组 [1,2,3].filter(x => x>1)[2,3]
reduce() 累积计算 累积值 [1,2,3].reduce((a,b)=>a+b,0)6
reduceRight() 从右累积 累积值 ['a','b'].reduceRight((a,b)=>a+b)'ba'
some() 是否有元素满足条件 true/false 自定义 [1,2,3].some(x=>x>2)true
every() 所有元素都满足条件 true/false 自定义 [1,2,3].every(x=>x>0)true
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
let arr = [1,4,5,6,3,5,66,23]

arr.forEach((item,index,arr) => { //foreach
console.log(`元素${item}的下标是${index}`);
})

console.log("================");

console.log(arr.map(x => x * 2)); //map
console.log("================");

console.log(arr.reduce((a,b) => a + b)); //reduce
console.log("================");

console.log(arr.filter(x => x % 2 == 0)); //filter
console.log("================");

console.log(arr.some(x => x > 2)); //有一个大于2就是true
console.log("================");

console.log(arr.every(x => x > 12)); //有一个不大于12就是false

7.函数

(1)函数定义

定义方式 语法 特点 案例
函数声明 function 函数名() {} 提升,可重复声明 function sayHi() { return 'Hi!'; }
函数表达式 const 函数接口名 = function() {} 不提升,更灵活 const sayHi = function() { return 'Hi!'; }
箭头函数 const 函数名 = () => {} 无this,简洁 const sayHi = () => 'Hi!';

(2)函数参数形式

注:函数可以有返回值或无返回值,有返回值要加上return !!!!!

参数类型 语法 描述 案例
默认参数 function(a=1, b=2) ES6,参数默认值 function greet(name='Guest') { return \Hello ${name}; }
剩余参数 function(...args) ES6,收集剩余参数 function sum(...numbers) { return numbers.reduce((a,b)=>a+b); }
解构参数 function({name, age}) ES6,对象解构 function showUser({name, age=18}) { console.log(name, age); }
arguments function() { arguments } 类数组,所有参数 function sumAll() { return [...arguments].reduce((a,b)=>a+b); }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
// 1. 默认参数		name,age,isActive三个参数
function createUser(name = '匿名用户', age = 18, isActive = true) {
return { name, age, isActive };
}
console.log(createUser()); // {name: '匿名用户', age: 18, isActive: true}
console.log(createUser('张三', 25)); // {name: '张三', age: 25, isActive: true}


// 2. 剩余参数 使用 ...参数名,返回值是数组
function orderPizza(size, ...toppings) {
console.log(`尺寸: ${size}`);
console.log(`配料: ${toppings.join(', ')}`);
}
orderPizza('大号', '芝士', '火腿', '蘑菇');
// 尺寸: 大号
// 配料: 芝士, 火腿, 蘑菇


// 3. 解构参数 使用{}包裹参数,类似于对象
function displayPerson({ name, age, city = '未知' }) {
console.log(`${name}${age}岁,来自${city}`);
}
const person = { name: '李四', age: 30 };
displayPerson(person); // 李四,30岁,来自未知


// 4. arguments(传统方式) 没有形参,但是可以输入实参!!!!!
function calculateAverage() {
const args = Array.from(arguments);
const sum = args.reduce((acc, val) => acc + val, 0);
return sum / args.length;
}
console.log(calculateAverage(85, 90, 78, 92)); // 86.25

(3)this关键字

谁调用指向谁,上一级,箭头函数没有this

(4)箭头函数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
//箭头函数用于简化函数声明
//普通函数
function common(){

}

//箭头函数
let commons = () => {

}

//当箭头函数只要一个参数并且返回值只有一条语句时,可以省略
let commonss = my => my
console.log(commonss(12)) //输出 12

8.对象

(1)对象创建方式

创建方式 语法 特点 案例
对象字面量 {} 最常用,简洁 const obj = {name: '张三', age: 25}
Object构造函数 new Object() 不推荐,冗长 const obj = new Object(); obj.name = '张三'
Object.create() Object.create(proto) 指定原型 const obj = Object.create(null)
构造函数 new 构造函数名() 创建多个实例 function Person(name) { this.name = name }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
 //方式1: {}
let obj1 = {name: "小陈",age: 20}

//方式2: new Object()
const obj2 = new Object()

//方式3: Object.create(对象名)
const obj3 = Object.create(null)

//方式4: 构造函数
function obj4(name) {
this.name = name
}

const objs = new obj4("小陈")
console.log(objs.name);

(2)对象属性描述

描述符 类型 默认值 描述
value any undefined 属性值
writable boolean false 是否可修改
enumerable boolean false 是否可枚举
configurable boolean false 是否可配置/删除
get function undefined getter函数
set function undefined setter函数

(3)相关方法

方法类别 方法名 描述 案例
属性操作 Object.keys() 获取可枚举属性名数组 Object.keys(obj)
属性操作 Object.values() 获取可枚举属性值数组 Object.values(obj)
属性操作 Object.entries() 获取键值对数组 Object.entries(obj)
属性操作 Object.hasOwn() 检查自身属性 Object.hasOwn(obj, 'key')
原型操作 Object.getPrototypeOf() 获取原型 Object.getPrototypeOf(obj)
原型操作 Object.setPrototypeOf() 设置原型 Object.setPrototypeOf(obj, proto)
对象操作 Object.assign() 合并对象(浅拷贝) Object.assign({}, obj1, obj2)
对象操作 Object.freeze() 冻结对象 Object.freeze(obj)
对象操作 Object.seal() 密封对象 Object.seal(obj)
对象操作 Object.create() 创建对象 Object.create(proto)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
const user = {
id: 1,
name: '张三',
age: 25,
email: 'zhangsan@example.com'
};

// 1. 属性遍历方法
console.log(Object.keys(user)); // ['id', 'name', 'age', 'email']
console.log(Object.values(user)); // [1, '张三', 25, 'zhangsan@example.com']
console.log(Object.entries(user));

// 2. 属性检查
console.log(Object.hasOwn(user, 'name')); // true
console.log(Object.hasOwn(user, 'toString')); // false(继承属性)
console.log('name' in user); // true
console.log('toString' in user); // true(包括继承属性)

// 3. 对象合并(浅拷贝)
const defaults = { theme: 'light', language: 'zh-CN' };
const userSettings = { theme: 'dark', notifications: true };
const finalSettings = Object.assign({}, defaults, userSettings);
console.log(finalSettings); // {theme: 'dark', language: 'zh-CN', notifications: true}

// 4. 对象冻结和密封
const obj = { x: 1, y: 2 };

// 密封:不能添加/删除属性,但可以修改现有属性
Object.seal(obj);
obj.x = 10; // ✅ 可以修改
obj.z = 30; // ❌ 不能添加新属性
delete obj.y; // ❌ 不能删除属性
console.log(Object.isSealed(obj)); // true

// 冻结:不能添加/删除/修改属性
const frozen = Object.freeze({ a: 1, b: 2 });
// frozen.a = 10; // ❌ 报错(严格模式)
console.log(Object.isFrozen(frozen)); // true

// 5. 原型操作
const parent = { parentMethod() { return '父方法'; } };
const child = { childMethod() { return '子方法'; } };

Object.setPrototypeOf(child, parent);
console.log(child.parentMethod()); // '父方法'
console.log(Object.getPrototypeOf(child) === parent); // true

9.类

(1)创建类

类声明 class ClassName {} 定义类 class Person {}
1
2
3
4
5
6
class person{

}

//使用
const obj = new person()

(2)构造函数

创建对象的时候自动调用此函数

构造函数 constructor() {} 实例初始化 constructor(name) { this.name = name }
1
2
3
4
5
6
7
8
9
class person{
name
constructor(name){
this.name = name
}
}

//使用
const obj = new person("小丽")

(3)实例和静态

实例方法 method() {} 实例方法 sayHello() { return 'Hello' }
静态方法 static method() {} 类方法 static create() { return new Person() }
静态属性 static prop = value 类属性 static species = '人类'
实例属性 prop = value 实例属性 age = 0
1
2
3
4
5
6
7
8
9
10
11
class person{
name //实例成员变量
static age //静态变量

info(){} //实例成员方法
static my(){} //静态变量

}

//静态变量和方法调用不要new对象
person.my() //对象.静态方法即可!!!

(4)私有属性和方法

私有字段 #privateField 私有字段 #password
私有方法 #privateMethod() {} 私有方法 #validate() {}
1
2
3
4
5
6
7
8
class person{
#name //私有变量
#info(){} //私有方法

}

const obj = new person()
// obj.name //此时无法调用!!!!

(5)Get和Set

专门用来访问私有属性

Getter get prop() {} 访问器属性 get fullName() {}
Setter set prop() {} 设置器属性 set age(value) {}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
class person{
#name //私有变量

get(){
return this.name
}

set(name){
this.name = name
}
}

const obj = new person()
obj.set("小陈") //给私有变量赋值
console.log(obj.get()); //获取私有变量

(6)继承

一个类继承另一个类的变量和方法

继承类 class Child extends Parent {} 类继承 class Student extends Person {}
调用父类构造函数 super() 在构造函数中调用父类构造函数 super(name, age)
调用父类方法 super.method() 调用父类方法 super.introduce()
方法重写 重新定义同名方法 子类重写父类方法 在子类中重新定义method()
静态继承 自动继承 子类继承父类静态成员 Student.species可访问
继承检查 instanceof 检查实例是否属于类 student instanceof Person
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
// 父类
class Animal {
constructor(name, species) {
this.name = name;
this.species = species;
this.energy = 100;
}

eat(food) {
this.energy += 10;
return `${this.name}吃了${food},能量+10`;
}

sleep(hours) {
this.energy += hours * 5;
return `${this.name}睡了${hours}小时,能量+${hours * 5}`;
}

makeSound() {
return `${this.name}发出声音`;
}

static isAnimal(obj) {
return obj instanceof Animal;
}
}

// 子类继承
class Dog extends Animal {
constructor(name, breed) {
super(name, '犬科'); // 必须调用super
this.breed = breed;
this.tricks = [];
}

// 方法重写
makeSound() {
return `${this.name}汪汪叫`;
}

// 调用父类方法
superEat(food) {
return super.eat(food) + '(特别版)';
}

// Getter
get isTired() {
return this.energy < 30;
}

// Setter
set energyLevel(value) {
if (value < 0) value = 0;
if (value > 100) value = 100;
this.energy = value;
}
}

// 使用示例
const myDog = new Dog('旺财', '金毛');
console.log(myDog.makeSound()); // 旺财汪汪叫
console.log(myDog.eat('狗粮')); // 旺财吃了狗粮,能量+10
console.log(myDog.superEat('骨头')); // 旺财吃了骨头,能量+10(特别版)

myDog.energyLevel = 150; // 通过setter设置,会被限制到100
console.log(myDog.energy); // 100
console.log(myDog.isTired); // false

// 继承检查
console.log(myDog instanceof Dog); // true
console.log(myDog instanceof Animal); // true
console.log(Animal.isAnimal(myDog)); // true

10.原型和原型链

(1)原型

原型(Prototype) 是 JavaScript 中实现继承的机制。每个对象都有一个内部链接指向另一个对象,这个被链接的对象就是原型
比如: 当我们创建数组(let arr = [1,2,3,4])时,为什么会自带方法??? 就是使用了原型链

核心概念:

  • 每个函数都有一个 prototype 属性(原型对象)
  • 每个对象都有一个 __proto__ 属性(指向其原型)
  • 原型本身也是一个对象,它也有自己的原型,形成原型链
概念 属性名 描述 示例
函数原型 prototype 函数特有的属性,用于构造函数创建实例 Person.prototype
对象原型 __proto__ 对象的内部属性,指向其原型 obj.__proto__
获取原型 Object.getPrototypeOf() 标准方法获取对象原型 Object.getPrototypeOf(obj)
设置原型 Object.setPrototypeOf() 设置对象原型 Object.setPrototypeOf(child, parent)
构造函数 constructor 原型对象指向构造函数 obj.constructor
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
//写一个函数
function person(){ //构造函数

}

const p = new person()

//概念,每个函数都会有prototype属性
console.log(person.prototype); // 输出 {}

//实例,每个实例都有一个 __proto__ 属性,它指向其原型
console.log(p.__proto__); //输出 {}

//此时这个实例和函数相等
console.log(person.prototype == p.__proto__); //true

(2)使用原型函数外增加方法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
function person(name){      //构造函数
this.name = name;
}

const p = new person("小陈")


//原型使用 在person里面新增方法
person.prototype.info = function() {
console.log(`你好我是${this.name}`);
}

p.info() //此时可以调用,只要创建该函数,自动获得info方法!!!!

//给数组新增求和方法
let arr = new Array(1,2,3)
Array.prototype.sum = function(){ //sum方法
return this.reduce((total,sum) => total + sum,0)
}

console.log(arr.sum());

11.API

(1)Math API

Math.abs() 绝对值 Math.abs(-5) → 5
Math.ceil() 向上取整 Math.ceil(1.2) → 2
Math.floor() 向下取整 Math.floor(1.8) → 1
Math.round() 四舍五入 Math.round(1.5) → 2
Math.max() 最大值 Math.max(1,2,3) → 3
Math.min() 最小值 Math.min(1,2,3) → 1
Math.sqrt() 平方根 Math.sqrt(9) → 3
Math.pow() 幂运算 Math.pow(2,3) → 8
Math.random() 随机数(0-1) Math.random()0.xxx

(2)Date API

构造函数 示例 结果 说明
new Date() new Date() 当前日期时间 无参数时返回当前时间
new Date(dateString) new Date("2024-01-01") 2024-01-01T00:00:00.000Z 解析日期字符串
方法 示例 返回值 范围 说明
getFullYear() date.getFullYear() 2024 年份 推荐使用,避免Y2K问题
getMonth() date.getMonth() 0-11 月份 0=1月,11=12月
getDate() date.getDate() 1-31 月份中的日期
getDay() date.getDay() 0-6 星期几 0=周日,6=周六
方法 示例 返回值 范围 说明
getHours() date.getHours() 0-23 小时 24小时制
getMinutes() date.getMinutes() 0-59 分钟
getSeconds() date.getSeconds() 0-59
getMilliseconds() date.getMilliseconds() 0-999 毫秒
getTime() date.getTime() 毫秒数 时间戳 从1970-01-01 UTC开始
方法 示例 返回值格式 说明
toLocaleString() date.toLocaleString() “2024/1/1 00:00:00” 本地格式字符串
toLocaleDateString() date.toLocaleDateString() “2024/1/1” 本地格式日期部分
toLocaleTimeString() date.toLocaleTimeString() “00:00:00” 本地格式时间部分
方法 示例 返回值 说明
Date.now() Date.now() 1640995200000 当前时间戳(毫秒)
Date.parse(dateString) Date.parse("2024-01-01") 1704067200000 解析日期字符串,返回时间戳
Date.UTC(year, month, ...) Date.UTC(2024, 0, 1) 1704067200000 返回UTC时间戳

(3)JSON API

API 作用 说明
JSON.stringify() 对象转JSON字符串 可传replacer和space参数
JSON.parse() JSON字符串转对象 可传reviver参数

(4)dataset API

dataset 是 DOM 元素的一个特殊属性,用于访问和操作 HTML5 中的 data-* 自定义数据属性。

操作 HTML 属性 JavaScript 访问 返回值类型
获取 data-name="value" element.dataset.name String
设置 data-name="newValue" element.dataset.name = "newValue" -
删除 -第一次删除不会生效 delete element.dataset.nameelement.removeAttribute(名) Boolean
检查 - 'name' in element.dataset Boolean
HTML 属性写法 JavaScript 访问方式 说明
data-user-id element.dataset.userId 连字符转驼峰
data-user-name element.dataset.userName 连字符转驼峰
data-user element.dataset.user 直接对应
data-is-active element.dataset.isActive 连字符转驼峰
data-123 element.dataset['123'] 数字开头需用方括号
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
<!DOCTYPE html>
<html>
<head>
<title>dataset 简洁示例</title>
<style>
.item {
padding: 10px;
margin: 5px;
background: #f0f0f0;
cursor: pointer;
}
.item:hover {
background: #e0e0e0;
}
</style>
</head>
<body>
<!-- HTML中定义 data-* 属性 -->
<div class="item" data-id="1" data-name="苹果" data-price="5.5" data-stock="true">
苹果 - ¥5.5/斤
</div>

<div class="item" data-id="2" data-name="香蕉" data-price="3.2" data-stock="false">
香蕉 - ¥3.2/斤
</div>

<div class="item" data-id="3" data-name="橙子" data-price="4.8" data-stock="true">
橙子 - ¥4.8/斤
</div>

<script>
// 获取所有商品元素
const items = document.querySelectorAll('.item');

// 为每个商品添加点击事件
items.forEach(item => {
item.addEventListener('click', function() {
// 使用 dataset 读取数据
const id = this.dataset.id; // "1" (字符串)
const name = this.dataset.name; // "苹果"
const price = this.dataset.price; // "5.5"
const stock = this.dataset.stock; // "true"

console.log(delete this.dataset.stock); //第一次删除这个data,但是下面还是能最少获取到一次

// 转换为合适的数据类型
const numPrice = parseFloat(price);
const isInStock = stock === 'true';

// 输出商品信息
console.log('商品ID:', id);
console.log('商品名称:', name);
console.log('商品价格:', numPrice, '元');
console.log('是否有货:', isInStock ? '有货' : '缺货');

// 修改数据
this.dataset.lastClick = new Date().toLocaleTimeString();
console.log('点击时间已记录:', this.dataset.lastClick);
});
});
</script>
</body>
</html>

12.DOM操作

(1)获取元素

方法 返回类型 是否实时 示例 说明
document.querySelector() Element/null querySelector('.active') 返回第一个匹配的元素
document.querySelectorAll() NodeList querySelectorAll('.item') 返回静态NodeList
Element.querySelector() Element/null div.querySelector('span') 在元素内查找第一个
Element.querySelectorAll() NodeList div.querySelectorAll('p') 在元素内查找所有

支持的参数选择:

选择器类型 示例 说明
标签选择器 'div' 选择所有div元素
类选择器 '.className' 选择指定类名的元素
ID选择器 '#idName' 选择指定ID的元素
属性选择器 '[type="text"]' 选择具有指定属性的元素
后代选择器 'div p' 选择div内的所有p
子元素选择器 'ul > li' 选择ul的直接子元素li
相邻兄弟 'h1 + p' 选择紧接在h1后的p
通用兄弟 'h1 ~ p' 选择h1后面的所有p
伪类选择器 ':first-child' 选择第一个子元素
组合选择器 'div.active' 同时满足多个条件
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div{
width: 200px;
height: 300px;
}
</style>
</head>
<body>
<div>123</div>
<div class="big">abc</div>
<div id = "x"></div>
<ul>
<li>测试1</li>
<li>测试2</li>
<li>测试3</li>
<li>测试4</li>
</ul>
<script>
//1.获取匹配的第一个元素 选择器必须加引号!!
const box = document.querySelector("div");//只会选择最前面的div <div class="box">123</div>
const bb = document.querySelector(".big");
const bbb = document.querySelector("#x");
const li = document.querySelector("ul li:first-child")//选择ul标签里面的第一个li 测试1
const lis = document.querySelectorAll("ul li");//选择ul所有标签

console.log(bb);
console.dir(box);
console.log(bbb);
console.log(li);//输出 ul里面的测试1
console.log(lis);//输出 [li,li,li,li] 数组表示
for(let i = 0; i < lis.length;i++){
console.log(lis[i]);//每一个li
}
</script>
</body>
</html>

注:过时的获取元素

方法 返回类型 是否实时 示例 说明
document.getElementById() Element/null document.getElementById('myId') 最常用,ID唯一,返回单个元素方法
document.getElementsByClassName() HTMLCollection getElementsByClassName('btn') 返回类名匹配的动态集合
document.getElementsByTagName() HTMLCollection getElementsByTagName('div') 返回标签名匹配的动态集合

(2)操作元素内容

2.1 设置元素内容

属性/方法 作用 HTML处理 性能 示例
textContent 获取/设置元素的文本内容 忽略HTML标签 div.textContent = '文本'
innerText 获取/设置元素的文本内容 考虑CSS样式,忽略隐藏元素 较慢 div.innerText = '文本'

2.2 设置元素内容,并且识别html标签

属性/方法 作用 性能 示例
innerHTML 获取/设置元素的HTML内容 div.innerHTML = '<b>加粗</b>'
outerHTML 获取/设置元素及其HTML内容 div.outerHTML = '<span>替换</span>'
1
2
3
4
const one = document.querySelector(".one")
const two = document.querySelector(".two")
one.textContent = '你好'
two.innerHTML = '<strong>hello</strong>' //会识别html样式

(3)元素属性操作

3.1 基本属性操作

方法 作用 返回值 实例
getAttribute() 获取属性值 String/null element.getAttribute('href')
setAttribute() 设置属性值 void element.setAttribute('class', 'active')
removeAttribute() 移除属性 void element.removeAttribute('disabled')
hasAttribute() 检查是否有属性 Boolean element.hasAttribute('data-id')
toggleAttribute() 切换属性 Boolean element.toggleAttribute('hidden')

3.2 特殊bool属性操作

属性 正确设置方法 说明
disabled input.disabled = truesetAttribute('disabled', '') 只要有属性就禁用
checked checkbox.checked = true 推荐用属性
selected option.selected = true 推荐用属性
readonly input.readOnly = true 注意大小写
multiple select.multiple = true
required input.required = true
hidden element.hidden = true HTML5新增

3.3 表单属性操作

属性 作用 可读/写 实例 说明
name 表单元素名称 读写 input.name = 'username' 提交时使用
value 元素当前值 读写 input.value = '张三' 最常用
type 输入类型 读写 input.type = 'email' 可动态更改
disabled 是否禁用 读写 input.disabled = true 布尔属性
readOnly 是否只读 读写 input.readOnly = true 注意大小写
required 是否必填 读写 input.required = true HTML5验证
placeholder 占位文本 读写 input.placeholder = '请输入' 提示文本
autocomplete 自动完成 读写 input.autocomplete = 'off' 控制浏览器自动填充
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
<!-- HTML -->
<input type="text" id="demoInput" name="demo" value="初始值">
<button onclick="demoBasicAttrs()">演示基本属性</button>

<!-- JavaScript -->
<script>
function demoBasicAttrs() {
const input = document.getElementById('demoInput');

console.log('=== 基本表单属性演示 ===');

// 1. 读取属性
console.log('当前name:', input.name); // "demo"
console.log('当前value:', input.value); // "初始值"
console.log('当前type:', input.type); // "text"
console.log('placeholder:', input.placeholder); // ""

// 2. 修改属性
input.name = 'username'; // 修改名称
input.value = '张三'; // 修改值
input.type = 'email'; // 修改类型(text→email)
input.placeholder = '请输入邮箱地址'; // 设置占位符

// 3. 布尔属性
input.disabled = true; // 禁用输入框
console.log('是否禁用:', input.disabled); // true

input.readOnly = true; // 设置为只读(注意大小写)
console.log('是否只读:', input.readOnly); // true

input.required = true; // 设置为必填
console.log('是否必填:', input.required); // true

// 4. 自动完成
input.autocomplete = 'off'; // 关闭自动完成
console.log('自动完成:', input.autocomplete); // "off"

// 5. 使用setAttribute/getAttribute
console.log('使用getAttribute获取name:', input.getAttribute('name'));
input.setAttribute('data-custom', '自定义数据');

// 6. 最终状态
setTimeout(() => {
console.log('最终HTML:', input.outerHTML);
console.log('所有属性:');
for (let attr of input.attributes) {
console.log(`${attr.name}: ${attr.value}`);
}
}, 100);
}
</script>

注:其他的如图片、视频、音频等都是这样,这里不演示了!!!!!

(4)元素样式操作

4.1 单或多样式增加

方法 语法示例 特点 适用场景
style 属性 element.style.color = 'red' 直接设置行内样式,优先级高 快速设置单个样式属性
cssText element.style.cssText = 'color:red; font-size:16px' 批量设置多个行内样式 需要一次性设置多个样式时
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<!DOCTYPE html>
<html lang="en">
<head>
<style>
.one{
font-size: 30px;
}
</style>
</head>
<body>
<p class="one">12</p>
<script>
const one = document.querySelector(".one")
one.style.color = 'red' //增加color样式颜色为红色
one.style.cssText = "letter-spacing:3px;outline: 2px solid #0066cc;" //增加多个样式
</script>
</body>
</html>

4.2 类样式操作

方法 语法示例 特点 适用场景
className element.className = 'active ...' 设置元素的 class 属性 应用预定义的 CSS 类
classList element.classList.add('active') 操作 class 列表的现代 API 添加/删除/切换单个或多个类
4.2.1 className
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<!DOCTYPE html>
<html lang="en">
<head>
<title>Document</title>
<style>
.one{
font-size: 30px;
}
.three{
color: red;
}
</style>
</head>
<body>
<p class="one">12</p>

<script>
const one = document.querySelector(".one")
//one.className = "three" //新增的类会替换到前面的类,只会生效一个
one.className = "one three" //可以使用空格分开,添加两个类
</script>
</body>
</html>
4,2.1 classList
方法 语法 描述 返回值
add() element.classList.add('class1', 'class2', ...) 添加一个或多个类 undefined
remove() element.classList.remove('class1', 'class2', ...) 移除一个或多个类 undefined
toggle() element.classList.toggle('className', force) 切换类的存在状态 Boolean (切换后是否存在)
contains() element.classList.contains('className') 检查是否包含指定类 Boolean
replace() element.classList.replace('oldClass', 'newClass') 替换一个类 Boolean (是否替换成功)
toString() element.classList.toString() 返回类列表字符串 String
forEach() element.classList.forEach(callback) 遍历所有类名 undefined
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.one{
font-size: 30px;
}
.three{
color: red;
}

.four{
outline: 1px solid green;
}

.five{
outline: 1px solid blue;
}

</style>
</head>
<body>
<p class="one">12</p>
<p class="two">14</p>

<script>
const one = document.querySelector(".one")
const two = document.querySelector(".two")
one.classList.add("three","four") //增加类
one.classList.remove("four") //删除类
one.classList.toggle("five") //如果该类存在,则删除,没有则添加
//one.classList.toggle("five",true) //强制添加 flase强制删除
one.classList.replace("five","four") //将 five类替换为 four类
console.log(one.classList.toString()); //打印全部类名,并为字符串
one.classList.forEach(x => console.log(x)) //打印类名
</script>
</body>
</html>

(5)定时器

类型 方法 作用 返回值 清除方法
延时执行 setTimeout(callback, delay) 延迟指定时间后执行一次 定时器ID clearTimeout(id)
间隔执行 setInterval(callback, delay) 每隔指定时间重复执行 定时器ID clearInterval(id)
下一帧执行 requestAnimationFrame(callback) 在下一帧重绘前执行 请求ID cancelAnimationFrame(id)
清除定时器 clearTimeout(定时器名)
clearInterval(定时器名)

5.1 setTimeout

语法: let 定时器名 = setTimeout(回调函数, 延迟时间(ms), 回调参数1, 回调参数2...);

1
2
3
4
5
6
7
8
9
10
11
12
// 基础用法
const timerId = setTimeout(() => {
console.log('3秒后执行');
}, 3000);

// 清除定时器
clearTimeout(timerId);

// 带参数
setTimeout((name, age) => {
console.log(name, age);
}, 1000, '张三', 25);

5.1.2 setInterval

语法:let 定时器名 = setInterval(回调函数, 延迟时间(ms), 回调参数1, 回调参数2...);

1
2
3
4
5
let count = 0;
const intervalId = setInterval(() => {
count++;
console.log(`执行第 ${count} 次`);
}, 1000);

(6)事件监听

方法 语法 移除方法 特点 兼容性
HTML属性 onclick="handleClick()" - 简单直接 所有浏览器
DOM属性 element.onclick = handleClick element.onclick = null 覆盖绑定 所有浏览器
addEventListener addEventListener(type, handler, options) removeEventListener 推荐,支持多个 IE9+

6.1 addEventListener

1
2
3
element.addEventListener('click', function(event) {
console.log('事件触发');
});

6.2 事件类型

6.2.1 鼠标事件
事件 触发时机 事件对象属性
click 点击(按下并释放) clientX, clientY, button
dblclick 双击 clientX, clientY, button
mousedown 鼠标按下 clientX, clientY, button
mouseup 鼠标释放 clientX, clientY, button
mousemove 鼠标移动 clientX, clientY, movementX, movementY
mouseenter 鼠标进入元素 clientX, clientY
mouseleave 鼠标离开元素 clientX, clientY
mouseover 鼠标进入元素或子元素 clientX, clientY, relatedTarget
mouseout 鼠标离开元素或子元素 clientX, clientY, relatedTarget
6.2.2 键盘事件
事件 触发时机 事件对象属性
keydown 按下任意键 key, code, ctrlKey, shiftKey
keyup 释放按键 key, code, ctrlKey, shiftKey
6.2.3 表单事件
事件 触发时机 事件对象属性
input 输入值改变 value, data
change 值改变并失去焦点 value
focus 获得焦点 target
blur 失去焦点 target
submit 表单提交 -
reset 表单重置 -
select 文本被选中 -
invalid 表单验证失败 -
6.2.4 窗口/文档事件
事件 触发时机 事件对象属性
load 资源加载完成 -
DOMContentLoaded DOM解析完成 -
beforeunload 页面即将卸载 returnValue
unload 页面正在卸载 -
resize 窗口大小改变 innerWidth, innerHeight
scroll 页面滚动 scrollX, scrollY
hashchange URL hash改变 oldURL, newURL
6.2.5 拖放事件
事件 触发时机 事件对象属性
dragstart 开始拖动 dataTransfer
drag 拖动中 dataTransfer, clientX, clientY
dragenter 拖动进入目标 dataTransfer
dragover 在目标上拖动 dataTransfer, clientX, clientY
dragleave 拖动离开目标 dataTransfer
drop 在目标上释放 dataTransfer, clientX, clientY
dragend 拖动结束 dataTransfer
6.2.6 触摸事件
事件 触发时机 事件对象属性
touchstart 触摸开始 touches, targetTouches
touchmove 触摸移动 touches, targetTouches
touchend 触摸结束 changedTouches
touchcancel 触摸取消 changedTouches
6.2.7 多媒体事件
事件 触发时机 事件对象属性
play 开始播放 -
pause 暂停播放 -
ended 播放结束 -
timeupdate 播放时间更新 currentTime
volumechange 音量改变 volume
loadeddata 媒体数据加载 -
6.2.8 剪贴板事件
事件 触发时机 事件对象属性
copy 复制 clipboardData
cut 剪切 clipboardData
paste 粘贴 clipboardData

6.3 常用的属性和方法

属性/方法 描述 示例
事件信息
event.type 事件类型 'click', 'keydown'
event.target 触发事件的元素 实际点击的元素
event.currentTarget 绑定事件的元素 事件监听器绑定的元素
event.eventPhase 事件阶段 (1捕获/2目标/3冒泡)
鼠标事件
event.clientX/Y 相对视口的坐标 鼠标在窗口中的位置
event.pageX/Y 相对文档的坐标 包含滚动距离的位置
event.screenX/Y 相对屏幕的坐标 鼠标在显示器中的位置
event.offsetX/Y 相对元素的坐标 鼠标在元素内部的位置
event.button 鼠标按钮 (0左键/1中键/2右键)
event.buttons 按下的所有按钮
键盘事件
event.key 按键名称 'Enter', 'a', 'Escape'
event.code 物理按键码 'KeyA', 'Enter', 'ArrowUp'
event.ctrlKey Ctrl是否按下 true/false
event.shiftKey Shift是否按下 true/false
event.altKey Alt是否按下 true/false
event.metaKey Meta/Command是否按下 true/false
表单事件
event.value 输入值
event.checked 复选框/单选是否选中
控制方法
event.preventDefault() 阻止默认行为
event.stopPropagation() 停止事件传播
event.stopImmediatePropagation() 阻止同元素的其他监听器
1. event.target - 事件触发源
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form id="survey">
<div class="question">
<p>1. 你喜欢什么颜色?</p>
<input type="checkbox" name="color" value="red"> 红色
<input type="checkbox" name="color" value="blue"> 蓝色
<input type="checkbox" name="color" value="green"> 绿色
</div>

<div class="question">
<p>2. 你的年龄段?</p>
<input type="radio" name="age" value="18-25"> 18-25
<input type="radio" name="age" value="26-35"> 26-35
<input type="radio" name="age" value="36+"> 36+
</div>

</form>

<script>
// 实时监听表单所有变化 1.获取最大的元素
document.getElementById('survey').addEventListener('change', function(event) {
const target = event.target; //2.如:点击"红色"复选框,target就是 <input type="checkbox" name="color" value="red">

// 知道是哪个问题发生了变化
const questionDiv = target.closest('.question'); //获取点击的父元素 closest('父元素名')
const questionText = questionDiv.querySelector('p').textContent;

console.log(`问题 "${questionText}" 的答案发生变化`);

// 实时更新预览
if (target.type === 'checkbox') {
const checkedBoxes = questionDiv.querySelectorAll('input:checked');
const values = Array.from(checkedBoxes).map(cb => cb.value);
console.log('选择的颜色:', values);
}
else if (target.type === 'radio') {
const selectedRadio = questionDiv.querySelector('input:checked');
console.log('选择的年龄段:', selectedRadio?.value);
}

});
//注: elment.targer 可以使用所有的DOM操作!!!!!
</script>
</body>
</html>
2. event.preventDefault() - 阻止默认行为
1
2
3
4
element.addEventListener('事件类型', function(event) {
event.preventDefault(); // 阻止默认行为 如:点击、跳转、拖拽等
// 执行自定义逻辑
});

(7)事件流

7.1 概念

指事件完整执行过程中流动路径 捕获:从大的往小的里面找 从父到子 冒泡:从小的往大的里面找 从子到父
操作 方法/属性 示例 作用 返回值
设置捕获监听 addEventListener(type, handler, true) elem.addEventListener('click', fn, true) 在捕获阶段监听事件 -
设置冒泡监听 addEventListener(type, handler, false) elem.addEventListener('click', fn, false) 在冒泡阶段监听事件(默认) -
获取当前阶段 event.eventPhase console.log(e.eventPhase) 查看事件当前阶段 1捕获/2目标/3冒泡
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
<script>
const btn = document.getElementById('btn');

// 阶段1:捕获阶段(从外到内)
document.addEventListener('click', function() {
console.log('1. 捕获:document');
}, true); // true表示捕获阶段

document.body.addEventListener('click', function() {
console.log('2. 捕获:body');
}, true);

// 阶段2:目标阶段
btn.addEventListener('click', function() {
console.log('3. 目标:按钮被点击');
}); // 默认冒泡阶段,但目标阶段也会执行

// 阶段3:冒泡阶段(从内到外)
document.body.addEventListener('click', function() {
console.log('4. 冒泡:body');
}); // 默认false,冒泡阶段

document.addEventListener('click', function() {
console.log('5. 冒泡:document');
});

// 输出顺序: 1. 捕获:document 2. 捕获:body 3. 目标:按钮被点击 4. 冒泡:body 5. 冒泡:document
</script>

7.2 事件相关属性

属性 描述 示例输出 阶段影响
event.target 事件触发的原始元素 <button id="btn"> 始终不变
event.currentTarget 当前处理事件的元素 <div id="parent"> 随阶段变化
event.eventPhase 当前阶段数字 1/2/3 实时变化
event.bubbles 事件是否冒泡 true 事件类型决定
event.cancelable 事件是否可取消 true 事件类型决定
判断目标 event.target.closest() e.target.closest('.item') 向上查找目标
检查目标 event.target.matches() e.target.matches('.btn') 检查元素匹配
操作 方法 示例 作用 注意
停止冒泡 event.stopPropagation() e.stopPropagation() 阻止事件继续传播 不影响当前元素的其他监听器
停止捕获 event.stopPropagation() 在捕获阶段调用 阻止捕获继续 目标阶段和冒泡都不会执行

7.3 事件委托

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
<!DOCTYPE html>
<html lang="en">
<head>
<style>
li{
list-style-type: none;
}
</style>
</head>
<body>
<ul>
<li>3</li>
<li>4</li>
<li>5</li>
<p>我不能变色</p>
</ul>
<script>
//点击每个小li,当前文字变色
//1.获得父元素
const ul = document.querySelector("ul");
ul.addEventListener("click",function(e){
// alert(11);
// this.style.color = "red";
console.dir(e.target);
//getName 的名字都是大写
if(e.target.tagName ==="LI"){
e.target.style.color = "red";//此时点一个li就只会变一个颜色
}
})
</script>
</body>
</html>

(8)节点操作

8.1 特殊节点获取

属性/方法 语法 返回值 描述
document document Document 文档根节点
documentElement document.documentElement Element <html> 元素
body document.body Element <body> 元素
head document.head Element <head> 元素
title document.title String 文档标题(可读写)
forms document.forms HTMLCollection 所有 <form> 元素
images document.images HTMLCollection 所有 <img> 元素
links document.links HTMLCollection 所有 <a><area> 元素

8.2 创建节点

方法 语法 返回值 示例 描述
createElement document.createElement(tagName) Element document.createElement('div') 创建元素节点
createTextNode document.createTextNode(data) Text document.createTextNode('Hello') 创建文本节点
createComment document.createComment(data) Comment document.createComment('注释') 创建注释节点
cloneNode element.cloneNode(true/false) 克隆节点 div.cloneNode(true)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
<div id="container"></div>

<script>
// 创建节点示例
const container = document.getElementById('container');

// 创建元素
const div = document.createElement('div');
div.className = 'box';

// 创建文本
const text = document.createTextNode('我是新创建的div');

// 组合
div.appendChild(text);

// 添加到页面
container.appendChild(div);
</script>

8.3 添加节点和插入

方法 语法 作用位置 示例
appendChild parent.appendChild(child) 末尾 parent.appendChild(newDiv)
insertBefore parent.insertBefore(new, ref) 指定前 parent.insertBefore(new, ref)
append parent.append(...nodes) 末尾 parent.append(div, span)
prepend parent.prepend(...nodes) 开头 parent.prepend(newDiv)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<ul id="list">
<li>项目1</li>
</ul>

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

// 1. 添加到末尾(常用)
const newItem = document.createElement('li');
newItem.textContent = '项目2';
list.appendChild(newItem);

// 2. 添加到开头
const firstItem = document.createElement('li');
firstItem.textContent = '项目0';
list.insertBefore(firstItem, list.firstChild);

8.4 删除和替换节点

方法 语法 作用 案例
removeChild parent.removeChild(child) 必须父节点删除 删除子节点 list.removeChild(item)
remove element.remove() 删除自身 div.remove()
replaceChild parent.replaceChild(new, old) 替换节点 list.replaceChild(new, old)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34

<div id="container">
<p id="text1">段落1</p>
<p id="text2">段落2</p>
<p id="text3">段落3</p>
</div>

<script>
<button onclick="removeFirst()">删除第一个</button>
<button onclick="replaceSecond()">替换第二个</button>
const container = document.getElementById('container');

function removeFirst() {
const first = document.getElementById('text1');
// 方法1:父元素删除子元素
container.removeChild(first);

// 方法2:元素自我删除(推荐)
// first.remove();
}

function replaceSecond() {
const second = document.getElementById('text2');
const newP = document.createElement('p');
newP.textContent = '新段落';
newP.style.color = 'red';

// 方法1:父元素替换子元素
container.replaceChild(newP, second);

// 方法2:元素自我替换(推荐)
// second.replaceWith(newP);
}
</script>

8.5 查找获取节点

属性 返回 说明 案例
parentNode 父节点 任意类型父节点 element.parentNode
parentElement 父元素 元素类型父节点 element.parentElement
children 子元素 所有子元素 element.children
firstElementChild 第一个子元素 element.firstElementChild
lastElementChild 最后一个子元素 element.lastElementChild
nextElementSibling 下一个兄弟元素 element.nextElementSibling
previousElementSibling 上一个兄弟元素 element.previousElementSibling
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
<div id="family">
<h3>父元素</h3>
<p>第一个子元素</p>
<span>第二个子元素</span>
<div>第三个子元素</div>
</div>

<button onclick="showRelations()">显示关系</button>

<script>
function showRelations() {
const family = document.getElementById('family');
const span = document.querySelector('span');

console.log('=== 节点关系 ===');
console.log('父元素:', family.parentElement.tagName); // BODY
console.log('子元素数量:', family.children.length); // 4
console.log('第一个子元素:', family.firstElementChild.tagName); // H3
console.log('最后一个子元素:', family.lastElementChild.tagName); // DIV

console.log('span的上一个兄弟:', span.previousElementSibling.tagName); // P
console.log('span的下一个兄弟:', span.nextElementSibling.tagName); // DIV
}
</script>

(9)尺寸和位置获取

9.1 内容尺寸

属性 描述 包含内容 是否包含滚动条 示例
clientWidth 元素内容宽度 内容 + 内边距 ❌ 不包含 div.clientWidth
clientHeight 元素内容高度 内容 + 内边距 ❌ 不包含 div.clientHeight
scrollWidth 实际内容宽度 全部内容宽度 ❌ 不包含 div.scrollWidth
scrollHeight 实际内容高度 全部内容高度 ❌ 不包含 div.scrollHeight

9.2 边框尺寸

属性 描述 包含内容 是否包含滚动条 示例
offsetWidth 元素整体宽度 内容 + 内边距 + 边框 ❌ 不包含 div.offsetWidth
offsetHeight 元素整体高度 内容 + 内边距 + 边框 ❌ 不包含 div.offsetHeight

9.3 元素位置获取(相对于父元素)

属性 描述 相对于 示例
offsetLeft 元素左边距 最近定位父元素 div.offsetLeft
offsetTop 元素上边距 最近定位父元素 div.offsetTop
offsetParent 定位父元素 - div.offsetParent

9.4 相对于视口

属性 描述 相对于 是否受滚动影响 示例
clientX/clientY 鼠标位置 浏览器视口 ✅ 受影响 event.clientX
pageX/pageY 鼠标位置 整个文档 ❌ 不受影响 event.pageX
screenX/screenY 鼠标位置 设备屏幕 ❌ 不受影响 event.screenX

9.5 getBoundingClientRect()

属性 描述 相对于 是否受滚动影响
.left 元素左边界 视口
.top 元素上边界 视口
.right 元素右边界 视口
.bottom 元素下边界 视口
.width 元素宽度 -
.height 元素高度 -
.x 同 .left 视口
.y 同 .top 视口

9.6 窗口尺寸

属性 描述 是否包含滚动条 示例
window.innerWidth 视口宽度 ✅ 包含 window.innerWidth
window.innerHeight 视口高度 ✅ 包含 window.innerHeight
window.outerWidth 浏览器窗口宽度 ✅ 包含 window.outerWidth
window.outerHeight 浏览器窗口高度 ✅ 包含 window.outerHeight

9.7 元素滚动

属性 描述 示例
element.scrollLeft 元素水平滚动距离 div.scrollLeft
element.scrollTop 元素垂直滚动距离 div.scrollTop

9.8 页面滚动位置

属性 描述 浏览器兼容性 示例
window.pageXOffset 页面水平滚动 现代浏览器 window.pageXOffset
window.pageYOffset 页面垂直滚动 现代浏览器 window.pageYOffset
window.scrollX 同 pageXOffset 现代浏览器 window.scrollX
window.scrollY 同 pageYOffset 现代浏览器 window.scrollY
document.documentElement.scrollTop 页面垂直滚动 兼容性好 document.documentElement.scrollTop
document.body.scrollTop 页面垂直滚动(旧) 旧浏览器 document.body.scrollTop

13.BOM操作

(1)location对象

location的数据类型是对象,它拆分并保存URL地址的各个组成部分。

属性 描述 示例URL 示例值
href 完整URL https://www.example.com:8080/path?query=1#hash 整个URL
protocol 协议 https:
host 主机+端口 www.example.com:8080
hostname 主机名 www.example.com
port 端口 8080
pathname 路径 /path
search 查询字符串 ?query=1
hash 锚点 #hash
origin https://www.example.com:8080

(2)history

浏览器操作

方法 描述 示例 注意
back() 后退 history.back() 同浏览器后退按钮
forward() 前进 history.forward() 同浏览器前进按钮
go() 跳转 history.go(-2) 负数后退,正数前进
属性 描述 示例
length 历史记录数量 history.length
state 当前状态对象 history.state

(3)navigator

获取浏览器信息

属性 描述 示例 用途
userAgent 浏览器信息 navigator.userAgent 浏览器嗅探
platform 操作系统 navigator.platform 系统检测
language 浏览器语言 navigator.language 国际化
cookieEnabled Cookie是否启用 navigator.cookieEnabled 功能检测
online 是否在线 navigator.onLine 网络状态
geolocation 地理位置API navigator.geolocation 位置服务
mediaDevices 媒体设备 navigator.mediaDevices 摄像头/麦克风
clipboard 剪贴板API navigator.clipboard 复制粘贴
storage 存储API navigator.storage 存储信息

(4)screen

打印屏幕信息

属性 描述 示例
width 屏幕宽度 screen.width
height 屏幕高度 screen.height
availWidth 可用宽度 screen.availWidth
availHeight 可用高度 screen.availHeight
colorDepth 颜色深度 screen.colorDepth
pixelDepth 像素深度 screen.pixelDepth
orientation 屏幕方向 screen.orientation

14.本地存储

(1)全部技术

技术 容量 生命周期 数据格式 特点 适用场景
LocalStorage 5-10MB 永久存储,除非手动删除 字符串 同源共享,同步操作 用户偏好设置、长期缓存
SessionStorage 5-10MB 会话期间(标签页关闭时清除) 字符串 标签页独立,同步操作 表单数据暂存、页面间临时数据传递
Cookies 约4KB 可设置过期时间 字符串 每次HTTP请求自动携带 用户认证、追踪用户行为
IndexedDB ≥250MB 永久存储 多种类型(对象、数组等) 异步操作,支持索引查询 大型数据、离线应用、复杂数据结构

注:最后一个不演示!!!!

(2)LocalStorage 本地存储

操作 语法 返回值 说明 示例
新增 / 修改 localStorage.setItem(k,v) undefined 存储键值对,如果键已存在则更新值 localStorage.setItem('username', '张三')
查询 / 获取 localStorage.getItem(key) `String null` 获取指定键的值,不存在则返回 null
删除单条 localStorage.removeItem(key) undefined 删除指定键的存储项 localStorage.removeItem('username')
清空全部 localStorage.clear() undefined 清除所有存储数据 localStorage.clear()
按索引取键名 localStorage.key(index) `String null` 根据索引获取键名,索引从0开始
获取存储条数 localStorage.length Number 获取当前存储的键值对数量 localStorage.length // 1
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<button class="btn">删除</button>
<button class="btn2">删除全部</button>
<script>
//localStorage
//添加
localStorage.setItem("db","itchen")
localStorage.setItem("age",19)
//获取
const db = localStorage.getItem("db") //取出为字符串
const age = localStorage.getItem("age") //虽然存储的数字,但取出来还是字符串!!
console.log(db);
console.log(age);
//删除
document.querySelector(".btn").addEventListener("click",() => {
localStorage.removeItem("db")
})
//删除全部
document.querySelector(".btn2").addEventListener("click",() => {
localStorage.clear()
})
//获取长度
console.log(localStorage.length);
</script>
</body>
</html>

(3)SessionStorage 会话存储

操作 语法 返回值 说明 示例
增 / 改 sessionStorage.setItem(key, value) undefined 存储键值对,如果键已存在则更新值 sessionStorage.setItem('username', '张三')
sessionStorage.getItem(key) `String null` 获取指定键的值,不存在则返回 null
删单条 sessionStorage.removeItem(key) undefined 删除指定键的存储项 sessionStorage.removeItem('username')
清空 sessionStorage.clear() undefined 清除当前会话的所有存储数据 sessionStorage.clear()
按索引取键名 sessionStorage.key(index) `String null` 根据索引获取键名
获取存储条数 sessionStorage.length Number 获取当前会话的存储数量 sessionStorage.length // 1
操作功能 语法书写 说明
设置 Cookie document.cookie = "键名=值; expires=过期时间; path=/; domain=域名" 可拼接参数,多个 Cookie 直接多次赋值即可;不设 expires 则为会话 Cookie
获取 Cookie document.cookie 返回值:所有 Cookie 拼接的字符串(格式:key1=val1; key2=val2),需自己解析
修改 Cookie document.cookie = "原键名=新值; expires=新时间; path=/;" 同名 + 同 path + 同 domain 即可覆盖修改
删除 Cookie document.cookie = "键名=; expires=过去的时间; path=/;" 把过期时间设为当前之前,即可删除对应 Cookie

15.正则表达式

创建: const 变量名 = /表达式/

(1)字符匹配

字符 描述 示例
. 匹配除换行符外的任意字符 /a.b/ 匹配 “axb”, “a b”
\d 匹配数字 /\d/ 匹配 “123” 中的 “1”
\D 匹配非数字 /\D/ 匹配 “a1b” 中的 “a”
\w 匹配字母、数字、下划线 /\w/ 匹配 “a_b1” 中的 “a”
\W 匹配非单词字符 /\W/ 匹配 “a b” 中的空格
\s 匹配空白字符 /\s/ 匹配 “a b” 中的空格
\S 匹配非空白字符 /\S/ 匹配 “a b” 中的 “a”

(2)位置匹配

字符 描述 示例
^ 匹配字符串开头 /^a/ 匹配 “abc” 中的 “a”
$ 匹配字符串结尾 /c$/ 匹配 “abc” 中的 “c”
\b 匹配单词边界 /\bword\b/ 匹配 “hello word ok” 中的 “word”
\B 匹配非单词边界 /\Bword\B/ 匹配 “swordfish” 中的 “word”

(3)量词

字符 描述 示例
* 0次或多次 /a*/ 匹配 “”, “a”, “aa”
+ 1次或多次 /a+/ 匹配 “a”, “aa”
? 0次或1次 /a?/ 匹配 “”, “a”
{n} 恰好n次 /a{3}/ 匹配 “aaa”
{n,} 至少n次 /a{2,}/ 匹配 “aa”, “aaa”
{n,m} n到m次 /a{2,4}/ 匹配 “aa”, “aaa”, “aaaa”

(4)字符类

语法 描述 示例
[abc] 匹配a、b或c中的任意一个 /[abc]/ 匹配 “apple” 中的 “a”
[^abc] 匹配除了a、b、c之外的字符 /[^abc]/ 匹配 “def” 中的 “d”
[a-z] 匹配a到z的小写字母 /[a-z]/ 匹配 “Hello” 中的 “e”
[A-Z] 匹配A到Z的大写字母 /[A-Z]/ 匹配 “Hello” 中的 “H”
[0-9] 匹配0到9的数字 /[0-9]/ 匹配 “123” 中的 “1”

(5)分组匹配

语法 描述 示例
(pattern) 捕获分组 /(\d{4})-(\d{2})/
(?:pattern) 非捕获分组 /(?:\d{4})-(\d{2})/
\n 反向引用 /(\w)\1/ 匹配 “aa”, “bb”

16.数组解构和对象解构

(1)数组解构

let [变量名1,变量名2….] = [数值] 或 数组名

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// ES5 传统方式
var arr = [1, 2, 3];
var a = arr[0];
var b = arr[1];
var c = arr[2];

// ES6 解构赋值
const [a, b, c] = [1, 2, 3];

//跳过元素
const [a, , c] = [1, 2, 3];

//部分解构 x= 1 y = 2
const [x,y] = [1,2,3,4,5,6]

//默认值 如果没有就是 12
const [x=10,y=20] = [12]

//剩余参数解构 此时 c = [3,4,5,6]
const [a,b,...c] = [1,2,3,4,5,6]

//作为函数参数解构
function add([a,b,c]){
return a + b + c
}
add([1,2,3])

(2)对象解构

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
const person = { name: '张三', age: 25, city: '北京' };

// 基础解构
const { name, age, city } = person;
console.log(name, age, city); // 张三 25 北京

// 使用不同的变量名
const { name: personName, age: personAge } = person;
console.log(personName, personAge); // 张三 25

// 解构部分属性
const { name } = person;
console.log(name); // 张三

//默认值
const { name, age = 18, city = '上海' } = person;

//剩余参数解构
const {name,...info} = person
console.log(info) // {age: 25,city: "北京"}

//作为函数参数解构
function printPerson({ name, age, city }) {
console.log(`${name}${age}岁,来自${city}`);
}
printPerson({ name: '张三', age: 25, city: '北京' });

17.异常处理

和Java一样 try{}catch(e){}finally{} throw 抛出异常

1
2
3
4
5
6
7
try{

}catch(e){
throw new error(e)
}finally{

}

六、javascript异步编程

1.同步和异步

特性 同步 异步
执行顺序 顺序执行,阻塞等待 不阻塞,后续代码可立即执行
控制流 线性,可预测 非线性的,基于事件
响应性 响应慢,用户界面可能冻结 响应快,保持界面流畅
复杂度 简单直观 较复杂,需要处理回调/Promise
适用场景 简单计算、文件读取 I/O操作、网络请求、UI交互
1
2
3
4
5
6
7
8
9
10
11
12
// 同步示例
console.log('开始同步任务');
const result = heavyCalculation(); // 阻塞3秒
console.log('任务完成:', result); // 3秒后执行
console.log('继续执行'); // 再等待

// 异步示例
console.log('开始异步任务');
setTimeout(() => {
console.log('异步任务完成');
}, 3000); // 不阻塞
console.log('继续执行'); // 立即执行

2.并发和并行

特性 同步 异步
执行顺序 顺序执行,阻塞等待 不阻塞,后续代码可立即执行
控制流 线性,可预测 非线性的,基于事件
响应性 响应慢,用户界面可能冻结 响应快,保持界面流畅
复杂度 简单直观 较复杂,需要处理回调/Promise
适用场景 简单计算、文件读取 I/O操作、网络请求、UI交互
1
2
3
4
5
6
7
8
9
10
11
12
// 同步示例
console.log('开始同步任务');
const result = heavyCalculation(); // 阻塞3秒
console.log('任务完成:', result); // 3秒后执行
console.log('继续执行'); // 再等待

// 异步示例
console.log('开始异步任务');
setTimeout(() => {
console.log('异步任务完成');
}, 3000); // 不阻塞
console.log('继续执行'); // 立即执行

3. Promise

(1)基本语法

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
//基本语法
const promise = new Promise((resolve,reject) => {
//返回成功数据,可以配合AJAX
resolve("数据")
//返回失败数据
reject(new error("失败"))
//两个只会触发一个!!!!
})

//then式调用
promise.then((result) => { //then表示打印执行成功的数据
console.log(result)
}).catch((error) => { //error表示打印失败的信息
console.log(error)
}).finally{ //无论成功还是失败都执行
console.log("一定执行")
}

(2)三种状态

1
2
3
4
5
6
7
8
9
10
// 1. Pending(进行中)- 初始状态
const pendingPromise = new Promise((resolve, reject) => {
// 还没有调用 resolve 或 reject
});

// 2. Fulfilled(已成功)- 操作成功完成
const fulfilledPromise = Promise.resolve('成功值');

// 3. Rejected(已失败)- 操作失败
const rejectedPromise = Promise.reject(new Error('失败原因'));

4. async/await

(1)基本语法

1
2
3
4
5
6
7
// await 只能用在 async 函数内部			await不能单独使用
async function fetchData() {
// 等待 Promise 完成
const response = await fetch('https://api.example.com/data');
const data = await response.json();
return data;
}

七、如有后续自动上传!!