HTML、CSS 和 JavaScript 基礎知識點
一、HTML 基礎
1. 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>
2. 常用 HTML 標簽
-
文本標簽:
<h1>到<h6>標題、<p>段落、<span>行內元素、<br>換行、<hr>水平線
-
列表:
<ul>無序列表、<ol>有序列表、<li>列表項、<dl>定義列表
-
表格:
<table>、<tr>行、<td>單元格、<th>表頭、<thead>、<tbody>、<tfoot>
-
表單:
<form>、<input>、<textarea>、<select>、<option>、<button>、<label>
-
多媒體:
<img>、<audio>、<video>、<iframe>
3. HTML5 新特性
- 語義化標簽:
<header>
,<footer>
,<nav>
,<article>
,<section>
,<aside>
- 表單增強:
<input type="date">
,<input type="email">
,<input type="range">
- 多媒體支持:
<video>
,<audio>
,<canvas>
- Web存儲:
localStorage
,sessionStorage
- Web Workers
- 地理定位 API
二、CSS 基礎
1. CSS 引入方式
<!-- 內聯樣式 -->
<div style="color: red;"></div><!-- 內部樣式表 -->
<style>div { color: red; }
</style><!-- 外部樣式表 -->
<link rel="stylesheet" href="styles.css">
2. CSS 選擇器
-
基礎選擇器:
/* 元素選擇器 */ p { color: blue; }/* 類選擇器 */ .class-name { color: red; }/* ID選擇器 */ #id-name { color: green; }/* 通配符選擇器 */ * { margin: 0; padding: 0; }
-
組合選擇器:
/* 后代選擇器 */ div p { color: red; }/* 子元素選擇器 */ div > p { color: blue; }/* 相鄰兄弟選擇器 */ h1 + p { color: green; }/* 通用兄弟選擇器 */ h1 ~ p { color: yellow; }
-
屬性選擇器:
/* 存在屬性 */ [title] { color: red; }/* 屬性值等于 */ [type="text"] { color: blue; }/* 屬性值包含 */ [class*="btn"] { color: green; }
-
偽類和偽元素:
/* 偽類 */ a:hover { color: red; } li:nth-child(odd) { background: #eee; }/* 偽元素 */ p::first-letter { font-size: 2em; } p::after { content: "★"; }
3. CSS 盒模型
-
組成:content(內容) + padding(內邊距) + border(邊框) + margin(外邊距)
-
box-sizing:
/* 標準盒模型 */ box-sizing: content-box; /* 默認值 *//* 怪異盒模型 */ box-sizing: border-box; /* 寬度包含padding和border */
4. 布局技術
-
浮動布局:
.float-left { float: left; } .clearfix::after {content: "";display: block;clear: both; }
-
Flex 布局:
.container {display: flex;justify-content: center; /* 主軸對齊 */align-items: center; /* 交叉軸對齊 */flex-wrap: wrap; /* 換行 */ } .item {flex: 1; /* 彈性比例 */ }
-
Grid 布局:
.container {display: grid;grid-template-columns: 1fr 2fr 1fr; /* 列定義 */grid-template-rows: 100px auto; /* 行定義 */gap: 10px; /* 間距 */ } .item {grid-column: 1 / 3; /* 跨列 */grid-row: 1; /* 行位置 */ }
5. 響應式設計
-
媒體查詢:
@media (max-width: 768px) {body { font-size: 14px; } }
-
視口單位:
.box {width: 50vw; /* 視口寬度的50% */height: 100vh; /* 視口高度的100% */font-size: 2vmin; /* 視口較小尺寸的2% */ }
三、JavaScript 基礎
1. 基礎語法
-
變量聲明:
// ES5 var name = "張三";// ES6+ let age = 25; // 塊級作用域變量 const PI = 3.14; // 常量
-
數據類型:
// 原始類型 typeof "hello" // "string" typeof 42 // "number" typeof true // "boolean" typeof undefined // "undefined" typeof null // "object" (歷史遺留問題) typeof Symbol() // "symbol" typeof BigInt(10) // "bigint"// 引用類型 typeof {} // "object" typeof [] // "object" typeof function(){} // "function"
2. 運算符
// 算術運算符
let sum = 10 + 5; // 15// 比較運算符
10 == "10" // true (值相等)
10 === "10" // false (值和類型都相等)// 邏輯運算符
true && false // false
true || false // true
!true // false// 三元運算符
let result = age > 18 ? '成年' : '未成年';
3. 流程控制
-
條件語句:
if (score >= 90) {console.log('優秀'); } else if (score >= 60) {console.log('及格'); } else {console.log('不及格'); }// switch語句 switch(day) {case 1: console.log('周一'); break;case 2: console.log('周二'); break;default: console.log('周末'); }
-
循環語句:
// for循環 for (let i = 0; i < 5; i++) {console.log(i); }// while循環 let j = 0; while (j < 5) {console.log(j);j++; }// for...of (ES6) for (let item of array) {console.log(item); }// for...in (遍歷對象屬性) for (let key in obj) {console.log(key, obj[key]); }
4. 函數
-
函數定義:
// 函數聲明 function add(a, b) {return a + b; }// 函數表達式 const multiply = function(a, b) {return a * b; };// 箭頭函數 (ES6) const divide = (a, b) => a / b;// 默認參數 (ES6) function greet(name = 'Guest') {console.log(`Hello, ${name}`); }// 剩余參數 (ES6) function sum(...numbers) {return numbers.reduce((acc, num) => acc + num, 0); }
-
高階函數:
// 函數作為參數 function operate(a, b, operation) {return operation(a, b); }operate(5, 3, (x, y) => x * y); // 15// 函數返回函數 function multiplier(factor) {return function(number) {return number * factor;}; }const double = multiplier(2); double(5); // 10
5. 對象和數組
-
對象:
// 對象字面量 const person = {name: '張三',age: 25,greet() {console.log(`我是${this.name}`);} };// 訪問屬性 person.name; // "張三" person['age']; // 25 person.greet(); // "我是張三"// ES6增強 const { name, age } = person; // 解構賦值 const newPerson = { ...person, age: 26 }; // 擴展運算符
-
數組:
// 數組方法 const numbers = [1, 2, 3, 4, 5];numbers.map(x => x * 2); // [2, 4, 6, 8, 10] numbers.filter(x => x > 2); // [3, 4, 5] numbers.reduce((a, b) => a + b); // 15// ES6數組操作 const newArr = [...numbers, 6, 7]; // [1, 2, 3, 4, 5, 6, 7] const [first, second, ...rest] = numbers; // 解構賦值
6. DOM 操作
// 獲取元素
const btn = document.getElementById('myButton');
const items = document.querySelectorAll('.item');// 事件監聽
btn.addEventListener('click', function(event) {console.log('按鈕被點擊了');
});// 修改內容
const heading = document.querySelector('h1');
heading.textContent = '新標題';
heading.style.color = 'red';// 創建元素
const newDiv = document.createElement('div');
newDiv.className = 'box';
document.body.appendChild(newDiv);// 表單處理
const form = document.querySelector('form');
form.addEventListener('submit', function(e) {e.preventDefault();const input = this.querySelector('input');console.log(input.value);
});
7. 異步編程
-
回調函數:
function fetchData(callback) {setTimeout(() => {callback('數據加載完成');}, 1000); }fetchData(function(data) {console.log(data); });
-
Promise:
function fetchData() {return new Promise((resolve, reject) => {setTimeout(() => {resolve('數據加載完成');// 或 reject('加載失敗');}, 1000);}); }fetchData().then(data => console.log(data)).catch(error => console.error(error));
-
async/await:
async function loadData() {try {const data = await fetchData();console.log(data);} catch (error) {console.error(error);} }loadData();
四、綜合案例
1. 簡單的待辦事項應用
<!DOCTYPE html>
<html>
<head><title>待辦事項</title><style>body { font-family: Arial, sans-serif; max-width: 600px; margin: 0 auto; }#todo-form { display: flex; margin-bottom: 20px; }#todo-input { flex: 1; padding: 8px; }button { padding: 8px 16px; background: #4CAF50; color: white; border: none; }ul { list-style: none; padding: 0; }li { padding: 10px; border-bottom: 1px solid #ddd; display: flex; }li.completed { text-decoration: line-through; color: #888; }.delete-btn { margin-left: auto; color: red; cursor: pointer; }</style>
</head>
<body><h1>待辦事項</h1><form id="todo-form"><input type="text" id="todo-input" placeholder="輸入待辦事項..." required><button type="submit">添加</button></form><ul id="todo-list"></ul><script>document.addEventListener('DOMContentLoaded', function() {const form = document.getElementById('todo-form');const input = document.getElementById('todo-input');const list = document.getElementById('todo-list');// 從本地存儲加載待辦事項let todos = JSON.parse(localStorage.getItem('todos')) || [];// 渲染待辦事項列表function renderTodos() {list.innerHTML = '';todos.forEach((todo, index) => {const li = document.createElement('li');if (todo.completed) {li.classList.add('completed');}li.innerHTML = `<span>${todo.text}</span><span class="delete-btn" data-index="${index}">×</span>`;li.addEventListener('click', function() {toggleTodo(index);});list.appendChild(li);});// 保存到本地存儲localStorage.setItem('todos', JSON.stringify(todos));}// 添加新待辦事項form.addEventListener('submit', function(e) {e.preventDefault();const text = input.value.trim();if (text) {todos.push({ text, completed: false });input.value = '';renderTodos();}});// 切換完成狀態function toggleTodo(index) {todos[index].completed = !todos[index].completed;renderTodos();}// 刪除待辦事項list.addEventListener('click', function(e) {if (e.target.classList.contains('delete-btn')) {const index = e.target.dataset.index;todos.splice(index, 1);renderTodos();}});// 初始渲染renderTodos();});</script>
</body>
</html>