HTML、CSS 和 JavaScript 基础知识点

发布于:2025-05-14 ⋅ 阅读:(19) ⋅ 点赞:(0)

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>

在这里插入图片描述


网站公告

今日签到

点亮在社区的每一天
去签到