我的个人博客

前端学习笔记

返回首页
技术分享 2025-12-20

HTML 基础

基本结构

!,html:5

常用标签

文本标签

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

<!-- 文本格式化 -->
<p>这是段落标签</p>
<strong>加粗文本</strong>
<em>倾斜文本</em>
<del>删除线文本</del>
<ins>下划线文本</ins>
<span>行内容器</span>
<br> <!-- 换行 -->
<hr> <!-- 水平线 -->

列表标签

<!-- 有序列表 -->
<ol type="1" start="1">
    <li>第一项</li>
    <li>第二项</li>
</ol>

<!-- 无序列表 -->
<ul type="disc"> <!-- disc: 实心圆点, circle: 空心圆, square: 方块 -->
    <li>项目一</li>
    <li>项目二</li>
</ul>

<!-- 自定义列表 -->
<dl>
    <dt>术语</dt>
    <dd>术语描述</dd>
</dl>

媒体标签

<!-- 图片 -->
<img src="图片地址" alt="加载失败提示" title="鼠标悬停提示" width="300" height="200">

<!-- 音频 -->
<audio controls loop autoplay>
    <source src="音频文件.mp3" type="audio/mpeg">
</audio>

<!-- 视频 -->
<video controls width="400" height="300">
    <source src="视频文件.mp4" type="video/mp4">
</video>

链接标签

<!-- 普通链接 -->
<a href="https://www.example.com" target="_blank">新窗口打开</a>
<a href="#section1">页面内锚点链接</a>

<!-- 下载链接 -->
<a href="文件.zip" download>下载文件</a>

<!-- 邮件链接 -->
<a href="mailto:example@email.com">发送邮件</a>

表单标签

<form action="/submit" method="post" autocomplete="off">
    <!-- 文本输入 -->
    <input type="text" placeholder="请输入用户名" required>
    
    <!-- 密码输入 -->
    <input type="password" placeholder="请输入密码">
    
    <!-- 单选按钮 -->
    <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"> 阅读
    <input type="checkbox" name="hobby" value="music"> 音乐
    
    <!-- 数字输入 -->
    <input type="number" min="1" max="100" value="18">
    
    <!-- 范围滑块 -->
    <input type="range" min="0" max="100" value="50">
    
    <!-- 颜色选择 -->
    <input type="color" value="#ff0000">
    
    <!-- 日期选择 -->
    <input type="date">
    
    <!-- 文件上传 -->
    <input type="file" accept=".jpg,.png">
    
    <!-- 下拉选择 -->
    <select name="city">
        <option value="beijing">北京</option>
        <option value="shanghai">上海</option>
        <option value="guangzhou">广州</option>
    </select>
    
    <!-- 文本域 -->
    <textarea rows="4" cols="50" placeholder="请输入留言"></textarea>
    
    <!-- 按钮 -->
    <button type="submit">提交</button>
    <button type="reset">重置</button>
    <button type="button">普通按钮</button>
</form>

表格标签

<table border="1">
    <thead>
        <tr>
            <th>姓名</th>
            <th>年龄</th>
            <th>城市</th>
        </tr>
    </thead>
    <tbody>
        <tr>
            <td>张三</td>
            <td>25</td>
            <td>北京</td>
        </tr>
        <tr>
            <td>李四</td>
            <td>30</td>
            <td>上海</td>
        </tr>
    </tbody>
</table>

<!-- 合并单元格 -->
<table>
    <tr>
        <td colspan="2">横向合并两列</td>
    </tr>
    <tr>
        <td rowspan="2">纵向合并两行</td>
        <td>单元格</td>
    </tr>
    <tr>
        <td>单元格</td>
    </tr>
</table>

语义化标签

<header>页面头部</header>
<nav>导航栏</nav>
<main>主要内容</main>
<article>文章内容</article>
<section>内容区块</section>
<aside>侧边栏</aside>
<footer>页面底部</footer>

CSS 基础

CSS 引入方式

<!-- 1. 行内样式 -->
<div style="color: red; font-size: 16px;">红色文字</div>

<!-- 2. 内部样式 -->
<head>
    <style>
        .red-text {
            color: red;
            font-size: 16px;
        }
    </style>
</head>

<!-- 3. 外部样式 -->
<head>
    <link rel="stylesheet" href="styles.css">
</head>

基础选择器

/* 1. 标签选择器 */
p {
    color: blue;
}

/* 2. 类选择器 */
.highlight {
    background-color: yellow;
}

/* 3. ID 选择器 */
#header {
    font-size: 24px;
}

/* 4. 通用选择器 */
* {
    margin: 0;
    padding: 0;
}

组合选择器

/* 1. 后代选择器 */
div p {
    color: red;
}

/* 2. 子选择器 */
div > p {
    color: blue;
}

/* 3. 相邻兄弟选择器 */
h1 + p {
    margin-top: 0;
}

/* 4. 通用兄弟选择器 */
h1 ~ p {
    color: gray;
}

/* 5. 并集选择器 */
h1, h2, h3 {
    font-family: Arial, sans-serif;
}

伪类选择器

/* 链接伪类 */
a:link { color: blue; }      /* 未访问 */
a:visited { color: purple; } /* 已访问 */
a:hover { color: red; }      /* 鼠标悬停 */
a:active { color: green; }   /* 激活状态 */

/* 结构伪类 */
:first-child { }     /* 第一个子元素 */
:last-child { }      /* 最后一个子元素 */
:nth-child(odd) { }  /* 奇数子元素 */
:nth-child(even) { } /* 偶数子元素 */
:not(.class) { }     /* 排除指定类 */

文本样式

/* 字体属性 */
font-family: "微软雅黑", Arial, sans-serif;
font-size: 16px;
font-weight: normal; /* normal(400), bold(700) */
font-style: normal;  /* normal, italic */

/* 文本属性 */
color: #333333;
text-align: center;    /* left, right, center, justify */
text-decoration: none; /* none, underline, overline, line-through */
text-indent: 2em;      /* 首行缩进 */
line-height: 1.5;      /* 行高 */
letter-spacing: 2px;   /* 字间距 */
word-spacing: 5px;     /* 词间距 */
text-transform: uppercase; /* uppercase, lowercase, capitalize */

背景样式

background-color: #f0f0f0;
background-image: url('image.jpg');
background-repeat: no-repeat; /* repeat, repeat-x, repeat-y */
background-position: center center;
background-size: cover; /* auto, cover, contain */
background-attachment: fixed; /* scroll, fixed */

/* 简写 */
background: #f0f0f0 url('image.jpg') no-repeat center center/cover;

盒子模型

/* 内边距 */
padding: 10px;           /* 四个方向 */
padding: 10px 20px;      /* 上下 左右 */
padding: 10px 20px 30px; /* 上 左右 下 */
padding: 10px 20px 30px 40px; /* 上 右 下 左 */

/* 外边距 */
margin: 10px;
margin: 10px 20px;
margin: 10px 20px 30px;
margin: 10px 20px 30px 40px;

/* 边框 */
border: 2px solid #ccc;
border-width: 2px;
border-style: solid; /* solid, dashed, dotted, double */
border-color: #ccc;

/* 圆角 */
border-radius: 5px;
border-radius: 50%; /* 圆形 */

/* 盒子模型 */
box-sizing: content-box; /* 默认值 */
box-sizing: border-box;  /* 包含 padding 和 border */

显示属性

display: block;       /* 块级元素:独占一行 */
display: inline;      /* 行内元素:一行多个 */
display: inline-block; /* 行内块:一行多个,可设宽高 */
display: none;        /* 隐藏元素 */
display: flex;        /* 弹性布局 */
display: grid;        /* 网格布局 */

定位

position: static;    /* 默认定位 */
position: relative;  /* 相对定位 */
position: absolute;  /* 绝对定位 */
position: fixed;     /* 固定定位 */
position: sticky;    /* 粘性定位 */

/* 定位偏移 */
top: 10px;
right: 20px;
bottom: 30px;
left: 40px;

/* 层级 */
z-index: 100;

浮动

float: left;
float: right;
float: none;

/* 清除浮动 */
clear: both;
clear: left;
clear: right;

/* 清除浮动方法 */
.clearfix::after {
    content: "";
    display: block;
    clear: both;
}

Flex 布局

/* 容器属性 */
display: flex;
flex-direction: row; /* row, column, row-reverse, column-reverse */
flex-wrap: nowrap;   /* nowrap, wrap, wrap-reverse */
justify-content: flex-start; /* flex-start, flex-end, center, space-between, space-around */
align-items: stretch;        /* stretch, flex-start, flex-end, center, baseline */
align-content: stretch;      /* stretch, flex-start, flex-end, center, space-between, space-around */

/* 项目属性 */
flex: 1;              /* flex-grow flex-shrink flex-basis */
flex-grow: 1;         /* 放大比例 */
flex-shrink: 1;       /* 缩小比例 */
flex-basis: auto;     /* 基础大小 */
align-self: auto;     /* 单独对齐 */
order: 1;             /* 排序顺序 */

过渡与动画

/* 过渡 */
transition: all 0.3s ease;
transition: property duration timing-function delay;

/* 动画 */
@keyframes slideIn {
    from {
        transform: translateX(-100%);
    }
    to {
        transform: translateX(0);
    }
}

animation: slideIn 0.5s ease-in-out;

JavaScript 基础

JavaScript 引入方式

<!-- 1. 行内 JavaScript -->
<button onclick="alert('Hello!')">点击我</button>

<!-- 2. 内部 JavaScript -->
<script>
    console.log('Hello World!');
</script>

<!-- 3. 外部 JavaScript -->
<script src="script.js"></script>

变量声明

// ES6+ 推荐使用 let 和 const
let name = "张三";        // 可变变量
const age = 25;          // 常量
var city = "北京";       // 旧式声明(不推荐)

// 变量命名规则
let userName = "user123";     // 驼峰命名法
let user_age = 25;           // 下划线命名法
let $element = document.body; // 可以以 $ 开头
let _private = "secret";      // 可以以 _ 开头

数据类型

// 基本数据类型
let str = "Hello";           // 字符串
let num = 42;                // 数字
let bool = true;             // 布尔值
let nothing = null;          // 空值
let undefinedVar;            // 未定义
let sym = Symbol("id");      // 符号

// 引用数据类型
let obj = { name: "张三", age: 25 };  // 对象
let arr = [1, 2, 3, 4, 5];           // 数组
let func = function() { return "Hello"; }; // 函数

// 类型检查
console.log(typeof str);      // "string"
console.log(typeof num);      // "number"
console.log(typeof bool);     // "boolean"
console.log(typeof obj);      // "object"
console.log(typeof arr);      // "object"
console.log(typeof func);     // "function"

字符串操作

let text = "Hello World";

// 字符串方法
console.log(text.length);           // 11
console.log(text.toUpperCase());    // "HELLO WORLD"
console.log(text.toLowerCase());    // "hello world"
console.log(text.indexOf("World")); // 6
console.log(text.slice(0, 5));      // "Hello"
console.log(text.substring(6, 11)); // "World"

// 字符串拼接
let firstName = "张";
let lastName = "三";
let fullName = firstName + lastName;     // "张三"
let fullName2 = `${firstName}${lastName}`; // "张三" (模板字符串)

// 字符串转换
let num = 42;
let str1 = String(num);     // "42"
let str2 = num.toString();  // "42"
let str3 = num + "";        // "42"

数字操作

// 基本运算
let a = 10, b = 3;
console.log(a + b);  // 13 (加法)
console.log(a - b);  // 7  (减法)
console.log(a * b);  // 30 (乘法)
console.log(a / b);  // 3.333... (除法)
console.log(a % b);  // 1  (取余)
console.log(a ** b); // 1000 (幂运算)

// 数学对象
console.log(Math.PI);           // 3.14159...
console.log(Math.random());     // 0-1 随机数
console.log(Math.floor(3.9));   // 3 (向下取整)
console.log(Math.ceil(3.1));    // 4 (向上取整)
console.log(Math.round(3.5));   // 4 (四舍五入)
console.log(Math.max(1, 2, 3)); // 3 (最大值)
console.log(Math.min(1, 2, 3)); // 1 (最小值)

// 数字转换
let str = "123";
let num1 = Number(str);    // 123
let num2 = parseInt(str);  // 123
let num3 = parseFloat("123.45"); // 123.45

数组操作

// 创建数组
let arr1 = [1, 2, 3, 4, 5];
let arr2 = new Array(1, 2, 3, 4, 5);
let arr3 = Array.of(1, 2, 3, 4, 5);

// 数组属性
console.log(arr1.length); // 5

// 数组方法
arr1.push(6);              // 末尾添加元素
arr1.pop();                // 末尾删除元素
arr1.unshift(0);           // 开头添加元素
arr1.shift();              // 开头删除元素
arr1.splice(1, 2, 7, 8);   // 从位置1删除2个元素,添加7,8
arr1.slice(1, 3);          // 截取子数组 [2, 3]
arr1.concat([6, 7]);        // 连接数组
arr1.join("-");             // 转换为字符串 "1-2-3-4-5"
arr1.indexOf(3);           // 查找元素索引
arr1.includes(3);          // 检查是否包含元素

// 数组遍历
arr1.forEach(function(item, index) {
    console.log(index + ": " + item);
});

let doubled = arr1.map(item => item * 2);      // 映射新数组
let evens = arr1.filter(item => item % 2 === 0); // 过滤数组
let sum = arr1.reduce((total, item) => total + item, 0); // 求和

对象操作

// 创建对象
let person = {
    name: "张三",
    age: 25,
    city: "北京",
    greet: function() {
        return "你好,我是" + this.name;
    }
};

// 访问属性
console.log(person.name);        // "张三"
console.log(person["age"]);      // 25
console.log(person.greet());     // "你好,我是张三"

// 添加/修改属性
person.email = "zhangsan@email.com";
person.age = 26;

// 删除属性
delete person.email;

// 对象方法
console.log(Object.keys(person));    // ["name", "age", "city", "greet"]
console.log(Object.values(person));  // ["张三", 26, "北京", function]
console.log(Object.entries(person)); // [["name", "张三"], ...]

// 对象遍历
for (let key in person) {
    console.log(key + ": " + person[key]);
}

条件语句

let score = 85;

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

// switch 语句
let day = "Monday";
switch (day) {
    case "Monday":
        console.log("星期一");
        break;
    case "Tuesday":
        console.log("星期二");
        break;
    default:
        console.log("其他");
}

// 三元运算符
let result = score >= 60 ? "及格" : "不及格";

循环语句

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

// while 循环
let count = 0;
while (count < 5) {
    console.log(count);
    count++;
}

// do-while 循环
do {
    console.log("至少执行一次");
} while (false);

// for...in 循环(遍历对象属性)
let obj = { a: 1, b: 2, c: 3 };
for (let key in obj) {
    console.log(key + ": " + obj[key]);
}

// for...of 循环(遍历数组/字符串)
let arr = [1, 2, 3, 4, 5];
for (let value of arr) {
    console.log(value);
}

let str = "Hello";
for (let char of str) {
    console.log(char);
}

函数

// 函数声明
function greet(name) {
    return "你好," + name;
}

// 函数表达式
let greet2 = function(name) {
    return "你好," + name;
};

// 箭头函数 (ES6+)
let greet3 = (name) => "你好," + name;

// 带默认参数的函数
function greet4(name = "朋友") {
    return "你好," + name;
}

// 调用函数
console.log(greet("张三"));
console.log(greet2("李四"));
console.log(greet3("王五"));
console.log(greet4()); // "你好,朋友"

// 函数作为参数
function calculate(a, b, operation) {
    return operation(a, b);
}

let add = (x, y) => x + y;
let multiply = (x, y) => x * y;

console.log(calculate(5, 3, add));      // 8
console.log(calculate(5, 3, multiply)); // 15

DOM 操作

// 获取元素
let element1 = document.getElementById('myId');
let element2 = document.querySelector('.myClass');
let element3 = document.querySelectorAll('div');

// 修改内容
element1.textContent = "新文本内容";
element1.innerHTML = "<strong>新HTML内容</strong>";

// 修改样式
element1.style.color = "red";
element1.style.fontSize = "20px";
element1.classList.add("active");
element1.classList.remove("inactive");
element1.classList.toggle("highlight");

// 修改属性
element1.setAttribute('data-id', '123');
element1.removeAttribute('title');
let attrValue = element1.getAttribute('data-id');

// 创建元素
let newDiv = document.createElement('div');
newDiv.textContent = "新元素";
document.body.appendChild(newDiv);

// 删除元素
let oldElement = document.getElementById('oldElement');
oldElement.parentNode.removeChild(oldElement);

// 事件监听
let button = document.querySelector('button');
button.addEventListener('click', function() {
    alert('按钮被点击了!');
});

// 鼠标事件
element.addEventListener('mouseenter', function() {
    this.style.backgroundColor = 'yellow';
});

element.addEventListener('mouseleave', function() {
    this.style.backgroundColor = '';
});

// 键盘事件
document.addEventListener('keydown', function(event) {
    console.log('按键:' + event.key);
});

常用内置对象

// Date 对象
let now = new Date();
console.log(now.getFullYear());     // 年份
console.log(now.getMonth() + 1);    // 月份 (0-11)
console.log(now.getDate());         // 日期
console.log(now.getDay());          // 星期 (0-6)
console.log(now.getHours());        // 小时
console.log(now.getMinutes());      // 分钟
console.log(now.getSeconds());      // 秒

// 格式化日期
let dateStr = now.toLocaleDateString('zh-CN');
let timeStr = now.toLocaleTimeString('zh-CN');

// JSON 对象
let person = { name: "张三", age: 25 };
let jsonStr = JSON.stringify(person); // 转为JSON字符串
let obj = JSON.parse(jsonStr);        // 解析JSON字符串

// 定时器
setTimeout(function() {
    console.log("3秒后执行");
}, 3000);

let interval = setInterval(function() {
    console.log("每秒执行一次");
}, 1000);

// 清除定时器
clearTimeout(timeoutId);
clearInterval(intervalId);