HTML前端笔记

HTML前端笔记

第一部分:HTML基础

1.1 HTML简介

什么是HTML?

HTML(HyperText Markup Language,超文本标记语言)是用于创建网页的标准标记语言。

前端三剑客的关系:

┌─────────────────────────────────────────────────┐
│                  前端三剑客                       │
├─────────────────────────────────────────────────┤
│                                                 │
│    HTML(骨)     →    定义网页结构              │
│       ↓                                         │
│    CSS(皮)      →    美化网页样式              │
│       ↓                                         │
│    JavaScript(魂) →  实现网页交互              │
│                                                 │
└─────────────────────────────────────────────────┘
技术 作用 比喻
HTML 定义网页结构和内容 人的骨架
CSS 美化网页外观样式 人的皮肤和衣服
JavaScript 实现网页动态交互 人的灵魂和行为

HTML特点:

  • 纯文本格式,可被人类阅读
  • 文件扩展名为 .html.htm
  • 由浏览器解析执行
  • 不区分大小写(推荐小写)

1.2 HTML文档结构

基本结构:

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>网页标题</title>
    <!-- 其他头部信息 -->
</head>
<body>
    <!-- 网页内容 -->
</body>
</html>

结构说明:

标签 说明
<!DOCTYPE html> 文档类型声明,告知浏览器使用HTML5标准
<html> 根元素,包含整个HTML文档
<head> 头部区域,包含元数据、标题、样式等
<meta> 元数据标签,定义字符编码、视口等
<title> 网页标题,显示在浏览器标签页
<body> 主体区域,包含可见的网页内容

常用meta标签:

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="description" content="网页描述">
<meta name="keywords" content="关键词1,关键词2">
<meta name="author" content="作者名">
<meta http-equiv="refresh" content="5;url=http://example.com">

1.3 常用HTML标签

1.3.1 文本标签

标题标签:

<h1>一级标题</h1>
<h2>二级标题</h2>
<h3>三级标题</h3>
<h4>四级标题</h4>
<h5>五级标题</h5>
<h6>六级标题</h6>

段落和文本格式:

<p>这是一个段落</p>

<br>           <!-- 换行 -->
<hr>           <!-- 水平线 -->

<b>粗体</b>
<strong>重要文本(粗体)</strong>
<i>斜体</i>
<em>强调文本(斜体)</em>
<u>下划线</u>
<s>删除线</s>
<del>删除文本</del>
<mark>高亮文本</mark>
<small>小号文本</small>

<sup>上标</sup>
<sub>下标</sub>

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

<blockquote>块引用</blockquote>
<span>行内元素,用于组合文本</span>

1.3.2 容器标签

<div>
    块级容器元素
    独占一行
    用于页面布局
</div>

<span>
    行内容器元素
    只占内容宽度
    用于文本样式
</span>

块级元素 vs 行内元素:

特性 块级元素 行内元素
独占一行
可设置宽高
可包含块级元素
示例 div, p, h1-h6, ul, table span, a, img, input

1.3.3 链接标签

<a href="https://www.example.com">普通链接</a>

<a href="https://www.example.com" target="_blank">新窗口打开</a>

<a href="#section1">页内锚点跳转</a>

<a href="mailto:test@example.com">发送邮件</a>

<a href="tel:+8612345678900">拨打电话</a>

<a href="javascript:alert('Hello');">JavaScript链接</a>

target属性值:

说明
_self 默认,在当前窗口打开
_blank 在新窗口打开
_parent 在父框架中打开
_top 在整个窗口中打开

1.3.4 图片标签

<img src="image.jpg" alt="图片描述">

<img src="image.jpg" alt="图片描述" width="200" height="150">

<img src="image.jpg" alt="图片描述" title="鼠标悬停提示">

<img src="image.jpg" alt="图片描述" loading="lazy">

img标签属性:

属性 说明
src 图片路径(必需)
alt 替代文本,图片无法显示时显示(必需)
title 鼠标悬停时的提示文本
width 宽度(像素或百分比)
height 高度(像素或百分比)
loading 懒加载(lazy/eager)

1.3.5 语义化标签(HTML5)

<header>页眉区域</header>

<nav>导航区域</nav>

<main>主要内容区域</main>

<article>文章内容</article>

<section>章节区域</section>

<aside>侧边栏区域</aside>

<footer>页脚区域</footer>

<figure>
    <img src="image.jpg" alt="图片">
    <figcaption>图片说明</figcaption>
</figure>

语义化标签的意义:

  • 提高代码可读性
  • 利于搜索引擎优化(SEO)
  • 方便屏幕阅读器解析
  • 便于团队维护

1.4 HTML表单

1.4.1 表单基础

<form action="/submit" method="POST">
    <label for="username">用户名:</label>
    <input type="text" id="username" name="username" placeholder="请输入用户名">
    
    <label for="password">密码:</label>
    <input type="password" id="password" name="password" placeholder="请输入密码">
    
    <button type="submit">提交</button>
</form>

form标签属性:

属性 说明
action 提交地址(URL)
method 提交方式(GET/POST)
enctype 编码类型
target 提交目标窗口
autocomplete 自动完成(on/off)

1.4.2 input输入类型

<input type="text" name="username">
<input type="password" name="password">
<input type="email" name="email">
<input type="number" name="age" min="0" max="150">
<input type="tel" name="phone">
<input type="url" name="website">
<input type="date" name="birthday">
<input type="time" name="time">
<input type="datetime-local" name="datetime">
<input type="month" name="month">
<input type="week" name="week">
<input type="color" name="color">
<input type="range" name="range" min="0" max="100">
<input type="file" name="file" accept=".jpg,.png">
<input type="hidden" name="token" value="abc123">
<input type="submit" value="提交">
<input type="reset" value="重置">
<input type="button" value="按钮">
<input type="image" src="submit.png" alt="提交">

input类型汇总:

类型 说明 示例
text 单行文本 用户名输入
password 密码(隐藏显示) 密码输入
email 邮箱(自动验证格式) 邮箱输入
number 数字 年龄输入
tel 电话号码 手机号输入
url 网址 网站输入
date 日期选择器 生日选择
time 时间选择器 时间选择
datetime-local 日期时间选择器 完整时间
color 颜色选择器 颜色选择
range 滑块 数值范围
file 文件上传 文件选择
hidden 隐藏字段 传递隐藏数据
submit 提交按钮 表单提交
reset 重置按钮 重置表单
button 普通按钮 自定义按钮
image 图片按钮 图形提交按钮

1.4.3 input常用属性

<input type="text" name="username" 
       placeholder="请输入用户名"
       value="默认值"
       maxlength="20"
       minlength="3"
       required
       readonly
       disabled
       autofocus
       autocomplete="off"
       pattern="[A-Za-z]{3,}"
       title="请输入3-20个字母">

属性说明:

属性 说明
name 字段名称(提交时使用)
value 默认值
placeholder 占位提示文本
required 必填字段
readonly 只读
disabled 禁用
autofocus 自动获取焦点
maxlength 最大字符数
minlength 最小字符数
min/max 数值范围限制
pattern 正则验证
autocomplete 自动完成
multiple 多选(文件/邮箱)
accept 文件类型限制

1.4.4 其他表单元素

文本域:

<textarea name="content" rows="5" cols="30" placeholder="请输入内容"></textarea>

下拉选择框:

<select name="city">
    <option value="">请选择城市</option>
    <option value="beijing">北京</option>
    <option value="shanghai" selected>上海</option>
    <option value="guangzhou">广州</option>
</select>

<select name="skills" multiple>
    <option value="html">HTML</option>
    <option value="css">CSS</option>
    <option value="js">JavaScript</option>
</select>

单选框和复选框:

单选框:
<input type="radio" name="gender" value="male" id="male" checked>
<label for="male">男</label>

<input type="radio" name="gender" value="female" id="female">
<label for="female">女</label>

复选框:
<input type="checkbox" name="hobby" value="reading" id="reading">
<label for="reading">阅读</label>

<input type="checkbox" name="hobby" value="music" id="music">
<label for="music">音乐</label>

<input type="checkbox" name="hobby" value="sports" id="sports" checked>
<label for="sports">运动</label>

按钮:

<button type="submit">提交按钮</button>
<button type="reset">重置按钮</button>
<button type="button">普通按钮</button>

标签关联:

<label for="username">用户名:</label>
<input type="text" id="username" name="username">

<label>
    <input type="checkbox" name="agree"> 同意条款
</label>

表单分组:

<fieldset>
    <legend>个人信息</legend>
    <label>姓名:<input type="text" name="name"></label>
    <label>年龄:<input type="number" name="age"></label>
</fieldset>

<fieldset>
    <legend>联系方式</legend>
    <label>电话:<input type="tel" name="phone"></label>
    <label>邮箱:<input type="email" name="email"></label>
</fieldset>

1.5 HTML表格与列表

1.5.1 表格

基本表格结构:

<table border="1">
    <caption>学生成绩表</caption>
    <thead>
        <tr>
            <th>姓名</th>
            <th>语文</th>
            <th>数学</th>
            <th>英语</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>张三</td>
            <td>90</td>
            <td>85</td>
            <td>88</td>
        </tr>
        <tr>
            <td>李四</td>
            <td>78</td>
            <td>92</td>
            <td>86</td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>平均分</td>
            <td>84</td>
            <td>88.5</td>
            <td>87</td>
        </tr>
    </tfoot>
</table>

合并单元格:

<table border="1">
    <tr>
        <td colspan="2">跨两列</td>
        <td>普通单元格</td>
    </tr>
    <tr>
        <td rowspan="2">跨两行</td>
        <td>B1</td>
        <td>C1</td>
    </tr>
    <tr>
        <td>B2</td>
        <td>C2</td>
    </tr>
</table>

表格标签说明:

标签 说明
<table> 表格容器
<caption> 表格标题
<thead> 表头区域
<tbody> 表体区域
<tfoot> 表尾区域
<tr> 表格行
<th> 表头单元格(加粗居中)
<td> 普通单元格
colspan 跨列合并
rowspan 跨行合并

1.5.2 列表

无序列表:

<ul type="disc">
    <li>列表项1</li>
    <li>列表项2</li>
    <li>列表项3</li>
</ul>

<ul type="circle">
    <li>空心圆点列表</li>
</ul>

<ul type="square">
    <li>实心方块列表</li>
</ul>

有序列表:

<ol type="1">
    <li>第一项</li>
    <li>第二项</li>
    <li>第三项</li>
</ol>

<ol type="A">
    <li>大写字母列表</li>
</ol>

<ol type="a">
    <li>小写字母列表</li>
</ol>

<ol type="I">
    <li>大写罗马数字</li>
</ol>

<ol type="i">
    <li>小写罗马数字</li>
</ol>

<ol start="5">
    <li>从5开始计数</li>
</ol>

<ol reversed>
    <li>倒序排列</li>
</ol>

定义列表:

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

嵌套列表:

<ul>
    <li>前端技术
        <ul>
            <li>HTML</li>
            <li>CSS</li>
            <li>JavaScript</li>
        </ul>
    </li>
    <li>后端技术
        <ul>
            <li>PHP</li>
            <li>Python</li>
            <li>Java</li>
        </ul>
    </li>
</ul>

1.6 HTML多媒体

1.6.1 音频

<audio controls>
    <source src="audio.mp3" type="audio/mpeg">
    <source src="audio.ogg" type="audio/ogg">
    您的浏览器不支持音频播放
</audio>

<audio src="music.mp3" controls autoplay loop muted></audio>

audio属性:

属性 说明
controls 显示播放控件
autoplay 自动播放
loop 循环播放
muted 静音
preload 预加载(auto/metadata/none)

1.6.2 视频

<video width="640" height="360" controls>
    <source src="video.mp4" type="video/mp4">
    <source src="video.webm" type="video/webm">
    您的浏览器不支持视频播放
</video>

<video src="movie.mp4" controls autoplay loop muted poster="poster.jpg"></video>

video属性:

属性 说明
controls 显示播放控件
autoplay 自动播放
loop 循环播放
muted 静音
poster 封面图片
width/height 宽高
preload 预加载

1.6.3 内嵌框架

<iframe src="https://www.example.com" width="600" height="400"></iframe>

<iframe src="page.html" frameborder="0" allowfullscreen></iframe>

<iframe src="video.html" sandbox="allow-scripts allow-same-origin"></iframe>

iframe属性:

属性 说明
src 嵌入页面地址
width/height 宽高
frameborder 边框(0/1)
allowfullscreen 允许全屏
sandbox 安全沙箱

第二部分:CSS基础

2.1 CSS简介

什么是CSS?

CSS(Cascading Style Sheets,层叠样式表)用于控制网页的外观样式。

CSS引入方式:

<!DOCTYPE html>
<html>
<head>
    <style>
        p {
            color: blue;
            font-size: 16px;
        }
    </style>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <p style="color: red; font-size: 20px;">内联样式</p>
    <p>内部样式</p>
    <p>外部样式</p>
</body>
</html>

三种引入方式对比:

方式 语法 优先级 适用场景
内联样式 style="属性:值" 最高 临时调试
内部样式 <style>标签 中等 单页面
外部样式 <link>引入 最低 多页面复用

CSS语法:

选择器 {
    属性名: 属性值;
    属性名: 属性值;
}

p {
    color: red;
    font-size: 16px;
    text-align: center;
}

2.2 CSS选择器

2.2.1 基础选择器

* {
    margin: 0;
    padding: 0;
}

p {
    color: blue;
}

.title {
    font-size: 24px;
}

#header {
    background: #333;
}

基础选择器说明:

选择器 语法 示例 说明
通配符 * * {} 选择所有元素
元素选择器 标签名 p {} 选择指定标签
类选择器 .类名 .title {} 选择指定类名
ID选择器 #ID名 #header {} 选择指定ID

2.2.2 组合选择器

div p {
    color: red;
}

div > p {
    color: blue;
}

h1 + p {
    margin-top: 0;
}

h1 ~ p {
    color: gray;
}

div, p, span {
    margin: 0;
}

组合选择器说明:

选择器 语法 示例 说明
后代选择器 空格 div p div内所有p
子代选择器 > div > p div直接子元素p
相邻兄弟 + h1 + p h1后面第一个p
通用兄弟 ~ h1 ~ p h1后面所有p
分组选择器 , div, p 选择div和p

2.2.3 属性选择器

input[type] {
    border: 1px solid #ccc;
}

input[type="text"] {
    width: 200px;
}

input[type="password"] {
    width: 200px;
}

a[href^="https"] {
    color: green;
}

a[href$=".pdf"] {
    color: red;
}

a[href*="example"] {
    font-weight: bold;
}

p[class~="active"] {
    color: blue;
}

p[class|="btn"] {
    padding: 5px 10px;
}

属性选择器说明:

选择器 说明
[attr] 具有指定属性
[attr="value"] 属性值等于指定值
[attr^="value"] 属性值以指定值开头
[attr$="value"] 属性值以指定值结尾
[attr*="value"] 属性值包含指定值
[attr~="value"] 属性值包含指定词
`[attr ="value"]`

2.2.4 伪类选择器

链接伪类:

a:link {
    color: blue;
}

a:visited {
    color: purple;
}

a:hover {
    color: red;
}

a:active {
    color: orange;
}

注意顺序: :link:visited:hover:active(LVHA)

结构伪类:

li:first-child {
    color: red;
}

li:last-child {
    color: blue;
}

li:nth-child(2) {
    color: green;
}

li:nth-child(odd) {
    background: #f0f0f0;
}

li:nth-child(even) {
    background: #e0e0e0;
}

li:nth-child(3n+1) {
    font-weight: bold;
}

p:first-of-type {
    font-size: 18px;
}

p:last-of-type {
    margin-bottom: 0;
}

p:only-child {
    text-align: center;
}

表单伪类:

input:focus {
    border-color: blue;
    outline: none;
}

input:disabled {
    background: #eee;
}

input:enabled {
    background: white;
}

input:checked {
    accent-color: blue;
}

input:required {
    border-left: 3px solid red;
}

input:valid {
    border-color: green;
}

input:invalid {
    border-color: red;
}

2.2.5 伪元素选择器

p::before {
    content: "★";
    color: red;
}

p::after {
    content: "→";
    color: blue;
}

p::first-letter {
    font-size: 24px;
    color: red;
}

p::first-line {
    font-weight: bold;
}

p::selection {
    background: yellow;
    color: black;
}

2.3 CSS盒模型

盒模型结构:

┌─────────────────────────────────────────────────┐
│                     margin                       │
│  ┌───────────────────────────────────────────┐  │
│  │                 border                     │  │
│  │  ┌─────────────────────────────────────┐  │  │
│  │  │              padding                │  │  │
│  │  │  ┌───────────────────────────────┐  │  │  │
│  │  │  │                               │  │  │  │
│  │  │  │           content             │  │  │  │
│  │  │  │                               │  │  │  │
│  │  │  └───────────────────────────────┘  │  │  │
│  │  └─────────────────────────────────────┘  │  │
│  └───────────────────────────────────────────┘  │
└─────────────────────────────────────────────────┘

盒模型属性:

div {
    width: 200px;
    height: 100px;
    
    padding: 10px;
    padding-top: 10px;
    padding-right: 20px;
    padding-bottom: 10px;
    padding-left: 20px;
    padding: 10px 20px;
    padding: 10px 20px 15px 25px;
    
    border: 1px solid #ccc;
    border-width: 1px;
    border-style: solid;
    border-color: #ccc;
    border-radius: 5px;
    
    margin: 10px;
    margin-top: 10px;
    margin-right: 20px;
    margin-bottom: 10px;
    margin-left: 20px;
    margin: 10px 20px;
    margin: 10px 20px 15px 25px;
    margin: 0 auto;
}

box-sizing属性:

div {
    box-sizing: content-box;
}

div {
    box-sizing: border-box;
}
说明
content-box 默认,宽高只包含内容
border-box 宽高包含内容、内边距和边框

2.4 CSS布局

2.4.1 display属性

div {
    display: block;
}

span {
    display: inline;
}

div {
    display: inline-block;
}

div {
    display: none;
}

div {
    display: flex;
}

div {
    display: grid;
}

display属性值:

说明
block 块级元素
inline 行内元素
inline-block 行内块元素
none 隐藏元素
flex 弹性布局
grid 网格布局

2.4.2 position定位

div {
    position: static;
}

div {
    position: relative;
    top: 10px;
    left: 20px;
}

div {
    position: absolute;
    top: 0;
    right: 0;
}

div {
    position: fixed;
    bottom: 20px;
    right: 20px;
}

div {
    position: sticky;
    top: 0;
}

position属性值:

说明 参照物
static 默认,正常文档流
relative 相对定位 自身原位置
absolute 绝对定位 最近的定位祖先
fixed 固定定位 浏览器窗口
sticky 粘性定位 滚动容器

2.4.3 Flex弹性布局

.container {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
    justify-content: center;
    align-items: center;
    align-content: space-between;
}

.item {
    flex: 1;
    flex-grow: 1;
    flex-shrink: 0;
    flex-basis: 200px;
    order: 1;
    align-self: flex-start;
}

Flex容器属性:

属性 说明
flex-direction 主轴方向 row/row-reverse/column/column-reverse
flex-wrap 换行方式 nowrap/wrap/wrap-reverse
justify-content 主轴对齐 flex-start/flex-end/center/space-between/space-around
align-items 交叉轴对齐 flex-start/flex-end/center/stretch/baseline
align-content 多行对齐 flex-start/flex-end/center/stretch/space-between

2.4.4 float浮动

div {
    float: left;
    width: 200px;
}

div {
    float: right;
    width: 200px;
}

.clearfix::after {
    content: "";
    display: block;
    clear: both;
}

2.5 CSS常用属性

2.5.1 文本属性

p {
    color: #333;
    font-size: 16px;
    font-family: "Microsoft YaHei", Arial, sans-serif;
    font-weight: bold;
    font-style: italic;
    
    text-align: center;
    text-decoration: underline;
    text-indent: 2em;
    line-height: 1.5;
    letter-spacing: 2px;
    word-spacing: 5px;
    
    text-transform: uppercase;
    text-shadow: 2px 2px 4px #ccc;
    white-space: nowrap;
    text-overflow: ellipsis;
    overflow: hidden;
}

2.5.2 背景属性

div {
    background-color: #f5f5f5;
    background-image: url("bg.jpg");
    background-repeat: no-repeat;
    background-position: center center;
    background-size: cover;
    background-attachment: fixed;
    
    background: #f5f5f5 url("bg.jpg") no-repeat center/cover fixed;
}

2.5.3 边框属性

div {
    border: 1px solid #ccc;
    border-radius: 5px;
    border-top: 1px solid #ccc;
    border-right: 2px dashed #999;
    border-bottom: 1px dotted #666;
    border-left: none;
    
    box-shadow: 2px 2px 10px rgba(0, 0, 0, 0.3);
}

第三部分:JavaScript基础

3.1 JavaScript简介

什么是JavaScript?

JavaScript是一种脚本语言,用于实现网页的动态交互功能。

JavaScript引入方式:

<!DOCTYPE html>
<html>
<head>
    <script>
        alert('内部脚本');
    </script>
    <script src="script.js"></script>
</head>
<body>
    <button onclick="alert('内联脚本')">点击</button>
</body>
</html>

3.2 JavaScript语法基础

3.2.1 变量与数据类型

var name = "张三";
let age = 25;
const PI = 3.14159;

let str = "Hello";
let num = 123;
let float = 3.14;
let bool = true;
let empty = null;
let notDefined = undefined;
let arr = [1, 2, 3, 4, 5];
let obj = { name: "张三", age: 25 };

console.log(typeof str);
console.log(typeof num);
console.log(typeof bool);
console.log(typeof arr);
console.log(typeof obj);
console.log(typeof null);
console.log(typeof undefined);

数据类型:

类型 说明 示例
String 字符串 "Hello"
Number 数字 123, 3.14
Boolean 布尔值 true, false
Null 空值 null
Undefined 未定义 undefined
Array 数组 [1, 2, 3]
Object 对象 {name: "张三"}

3.2.2 运算符

let a = 10;
let b = 3;

console.log(a + b);
console.log(a - b);
console.log(a * b);
console.log(a / b);
console.log(a % b);
console.log(a ** b);

a++;
a--;
a += 5;
a -= 3;

console.log(a == b);
console.log(a === b);
console.log(a != b);
console.log(a !== b);
console.log(a > b);
console.log(a < b);
console.log(a >= b);
console.log(a <= b);

console.log(true && false);
console.log(true || false);
console.log(!true);

let result = a > b ? "a大" : "b大";

3.2.3 流程控制

条件语句:

let score = 85;

if (score >= 90) {
    console.log("优秀");
} else if (score >= 80) {
    console.log("良好");
} else if (score >= 60) {
    console.log("及格");
} else {
    console.log("不及格");
}

let day = 3;
switch (day) {
    case 1:
        console.log("星期一");
        break;
    case 2:
        console.log("星期二");
        break;
    case 3:
        console.log("星期三");
        break;
    default:
        console.log("其他");
}

循环语句:

for (let i = 0; i < 5; i++) {
    console.log(i);
}

let arr = [1, 2, 3, 4, 5];
for (let i in arr) {
    console.log(i);
}

for (let item of arr) {
    console.log(item);
}

let i = 0;
while (i < 5) {
    console.log(i);
    i++;
}

let j = 0;
do {
    console.log(j);
    j++;
} while (j < 5);

3.2.4 函数

function sayHello() {
    console.log("Hello!");
}

function greet(name) {
    return "Hello, " + name + "!";
}

let add = function(a, b) {
    return a + b;
};

let multiply = (a, b) => a * b;

let result = greet("张三");
console.log(add(1, 2));
console.log(multiply(3, 4));

3.2.5 数组方法

let arr = [1, 2, 3, 4, 5];

arr.push(6);
arr.pop();
arr.unshift(0);
arr.shift();

arr.splice(2, 1);
arr.splice(2, 0, 3);

let newArr = arr.slice(1, 3);

let joined = arr.join(",");
let str = "a,b,c";
let arr2 = str.split(",");

arr.forEach(function(item, index) {
    console.log(index + ": " + item);
});

let doubled = arr.map(function(item) {
    return item * 2;
});

let filtered = arr.filter(function(item) {
    return item > 2;
});

let found = arr.find(function(item) {
    return item > 2;
});

let hasEven = arr.some(function(item) {
    return item % 2 === 0;
});

let allPositive = arr.every(function(item) {
    return item > 0;
});

let sum = arr.reduce(function(total, item) {
    return total + item;
}, 0);

3.2.6 字符串方法

let str = "Hello, World!";

console.log(str.length);
console.log(str.charAt(0));
console.log(str[0]);
console.log(str.indexOf("o"));
console.log(str.lastIndexOf("o"));
console.log(str.includes("World"));
console.log(str.startsWith("Hello"));
console.log(str.endsWith("!"));

console.log(str.substring(0, 5));
console.log(str.slice(0, 5));
console.log(str.slice(-6));

console.log(str.toLowerCase());
console.log(str.toUpperCase());

console.log(str.trim());
console.log(str.replace("World", "JavaScript"));

let arr = str.split(", ");
console.log(arr.join(" - "));

3.3 DOM操作

3.3.1 获取元素

let element = document.getElementById("header");

let elements = document.getElementsByClassName("item");

let elements = document.getElementsByTagName("p");

let element = document.querySelector(".title");
let element = document.querySelector("#header");
let element = document.querySelector("div.container p");

let elements = document.querySelectorAll(".item");
let elements = document.querySelectorAll("p");

3.3.2 操作元素内容

let element = document.getElementById("content");

console.log(element.innerHTML);
element.innerHTML = "<strong>新内容</strong>";

console.log(element.textContent);
element.textContent = "纯文本内容";

console.log(element.innerText);
element.innerText = "可见文本";

3.3.3 操作元素属性

let img = document.querySelector("img");

console.log(img.getAttribute("src"));
img.setAttribute("src", "new-image.jpg");
img.removeAttribute("alt");

console.log(img.src);
img.src = "new-image.jpg";

let link = document.querySelector("a");
console.log(link.href);
link.href = "https://www.example.com";

let input = document.querySelector("input");
console.log(input.value);
input.value = "新值";

console.log(input.type);
input.type = "password";

3.3.4 操作元素样式

let element = document.getElementById("box");

element.style.color = "red";
element.style.backgroundColor = "#f5f5f5";
element.style.fontSize = "20px";
element.style.width = "200px";
element.style.height = "100px";

console.log(element.style.color);

element.classList.add("active");
element.classList.remove("active");
element.classList.toggle("active");
element.classList.contains("active");
element.classList.replace("old", "new");

3.3.5 创建和删除元素

let div = document.createElement("div");
div.innerHTML = "新创建的div";
div.className = "new-div";
div.id = "newDiv";

let container = document.getElementById("container");
container.appendChild(div);

let p = document.createElement("p");
p.textContent = "段落";
container.insertBefore(p, div);

container.removeChild(div);

div.remove();

container.innerHTML = "";

3.4 事件处理

3.4.1 事件绑定方式

<button onclick="handleClick()">点击我</button>

<button id="btn">点击我</button>

<script>
function handleClick() {
    alert("按钮被点击");
}

let btn = document.getElementById("btn");
btn.onclick = function() {
    alert("按钮被点击");
};

btn.addEventListener("click", function() {
    alert("按钮被点击");
});

function handleClick(event) {
    console.log(event.type);
    console.log(event.target);
    console.log(event.clientX, event.clientY);
}

btn.addEventListener("click", handleClick);
btn.removeEventListener("click", handleClick);
</script>

3.4.2 常用事件

鼠标事件:

element.addEventListener("click", function() {});
element.addEventListener("dblclick", function() {});
element.addEventListener("mouseenter", function() {});
element.addEventListener("mouseleave", function() {});
element.addEventListener("mouseover", function() {});
element.addEventListener("mouseout", function() {});
element.addEventListener("mousedown", function() {});
element.addEventListener("mouseup", function() {});
element.addEventListener("mousemove", function() {});

键盘事件:

document.addEventListener("keydown", function(event) {
    console.log(event.key);
    console.log(event.keyCode);
    console.log(event.ctrlKey);
    console.log(event.shiftKey);
    console.log(event.altKey);
});

document.addEventListener("keyup", function(event) {});
document.addEventListener("keypress", function(event) {});

表单事件:

input.addEventListener("focus", function() {});
input.addEventListener("blur", function() {});

input.addEventListener("input", function() {
    console.log(this.value);
});

input.addEventListener("change", function() {});

form.addEventListener("submit", function(event) {
    event.preventDefault();
});

select.addEventListener("change", function() {
    console.log(this.value);
});

窗口事件:

window.addEventListener("load", function() {});

window.addEventListener("DOMContentLoaded", function() {});

window.addEventListener("resize", function() {
    console.log(window.innerWidth, window.innerHeight);
});

window.addEventListener("scroll", function() {
    console.log(window.scrollY);
});

3.4.3 事件对象

element.addEventListener("click", function(event) {
    console.log(event.type);
    console.log(event.target);
    console.log(event.currentTarget);
    console.log(event.clientX, event.clientY);
    console.log(event.pageX, event.pageY);
    console.log(event.screenX, event.screenY);
    
    event.preventDefault();
    event.stopPropagation();
    event.stopImmediatePropagation();
});

3.5 表单验证

3.5.1 基础验证

<form id="myForm" onsubmit="return validateForm()">
    <label>用户名:<input type="text" id="username" name="username"></label>
    <span id="usernameError" class="error"></span>
    
    <label>邮箱:<input type="email" id="email" name="email"></label>
    <span id="emailError" class="error"></span>
    
    <label>密码:<input type="password" id="password" name="password"></label>
    <span id="passwordError" class="error"></span>
    
    <button type="submit">提交</button>
</form>

<script>
function validateForm() {
    let username = document.getElementById("username").value;
    let email = document.getElementById("email").value;
    let password = document.getElementById("password").value;
    let isValid = true;
    
    if (username.trim() === "") {
        document.getElementById("usernameError").textContent = "用户名不能为空";
        isValid = false;
    } else if (username.length < 3) {
        document.getElementById("usernameError").textContent = "用户名至少3个字符";
        isValid = false;
    } else {
        document.getElementById("usernameError").textContent = "";
    }
    
    let emailPattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailPattern.test(email)) {
        document.getElementById("emailError").textContent = "请输入有效的邮箱地址";
        isValid = false;
    } else {
        document.getElementById("emailError").textContent = "";
    }
    
    if (password.length < 6) {
        document.getElementById("passwordError").textContent = "密码至少6个字符";
        isValid = false;
    } else {
        document.getElementById("passwordError").textContent = "";
    }
    
    return isValid;
}
</script>

3.5.2 实时验证

let username = document.getElementById("username");

username.addEventListener("input", function() {
    let value = this.value;
    let error = document.getElementById("usernameError");
    
    if (value.length < 3) {
        error.textContent = "用户名至少3个字符";
        this.classList.add("invalid");
        this.classList.remove("valid");
    } else {
        error.textContent = "";
        this.classList.remove("invalid");
        this.classList.add("valid");
    }
});

let email = document.getElementById("email");

email.addEventListener("blur", function() {
    let value = this.value;
    let error = document.getElementById("emailError");
    let pattern = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    
    if (!pattern.test(value)) {
        error.textContent = "请输入有效的邮箱地址";
        this.classList.add("invalid");
    } else {
        error.textContent = "";
        this.classList.remove("invalid");
    }
});

3.5.3 正则表达式验证

let patterns = {
    username: /^[a-zA-Z0-9_]{3,20}$/,
    email: /^[^\s@]+@[^\s@]+\.[^\s@]+$/,
    phone: /^1[3-9]\d{9}$/,
    password: /^(?=.*[a-z])(?=.*[A-Z])(?=.*\d)[a-zA-Z\d]{8,}$/,
    url: /^https?:\/\/[\w\-]+(\.[\w\-]+)+[/#?]?.*$/,
    idCard: /^\d{17}[\dXx]$/
};

function validate(value, pattern) {
    return pattern.test(value);
}

console.log(validate("test@example.com", patterns.email));
console.log(validate("13812345678", patterns.phone));

第四部分:前端安全基础

4.1 XSS防护

function escapeHtml(str) {
    return str.replace(/[&<>"']/g, function(match) {
        return {
            '&': '&amp;',
            '<': '&lt;',
            '>': '&gt;',
            '"': '&quot;',
            "'": '&#39;'
        }[match];
    });
}

let userInput = "<script>alert('XSS')</script>";
let safeOutput = escapeHtml(userInput);
document.getElementById("output").textContent = safeOutput;

4.2 CSRF防护

<form action="/submit" method="POST">
    <input type="hidden" name="csrf_token" value="<?php echo $_SESSION['csrf_token']; ?>">
    <input type="text" name="data">
    <button type="submit">提交</button>
</form>

4.3 输入验证

function sanitizeInput(input) {
    return input
        .replace(/</g, "&lt;")
        .replace(/>/g, "&gt;")
        .replace(/"/g, "&quot;")
        .replace(/'/g, "&#39;")
        .trim();
}

function validateInput(input, type) {
    switch(type) {
        case 'email':
            return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(input);
        case 'phone':
            return /^1[3-9]\d{9}$/.test(input);
        case 'url':
            return /^https?:\/\/[\w\-]+(\.[\w\-]+)+[/#?]?.*$/.test(input);
        default:
            return input.length > 0;
    }
}

4.4 安全的DOM操作

let element = document.getElementById("output");

element.textContent = userInput;

element.innerText = userInput;

element.innerHTML = escapeHtml(userInput);

let script = document.createElement("script");
script.textContent = userInput;
document.body.appendChild(script);

附录:常用代码片段

表单自动验证

<form id="autoValidateForm">
    <input type="text" name="username" required minlength="3" maxlength="20" pattern="[a-zA-Z0-9_]+">
    <input type="email" name="email" required>
    <input type="password" name="password" required minlength="6">
    <button type="submit">提交</button>
</form>

<script>
document.getElementById("autoValidateForm").addEventListener("submit", function(e) {
    if (!this.checkValidity()) {
        e.preventDefault();
        let inputs = this.querySelectorAll("input");
        inputs.forEach(function(input) {
            if (!input.validity.valid) {
                console.log(input.name + ": " + input.validationMessage);
            }
        });
    }
});
</script>

动态表格

function createTable(data) {
    let table = document.createElement("table");
    let thead = document.createElement("thead");
    let tbody = document.createElement("tbody");
    
    let headerRow = document.createElement("tr");
    Object.keys(data[0]).forEach(function(key) {
        let th = document.createElement("th");
        th.textContent = key;
        headerRow.appendChild(th);
    });
    thead.appendChild(headerRow);
    
    data.forEach(function(item) {
        let row = document.createElement("tr");
        Object.values(item).forEach(function(value) {
            let td = document.createElement("td");
            td.textContent = value;
            row.appendChild(td);
        });
        tbody.appendChild(row);
    });
    
    table.appendChild(thead);
    table.appendChild(tbody);
    return table;
}
posted @ 2026-02-28 13:43  丝云戏千鹤  阅读(42)  评论(0)    收藏  举报