web前端HTML+CSS+JavaScript零基础到精通

73 阅读4分钟

Web前端开发全栈教程:从入门到精通实战指南 一、HTML5+CSS3基础与实战 HTML5和CSS3是现代Web开发的基石,掌握它们是成为前端开发者的第一步。以下是核心知识点和代码示例:

  1. 语义化HTML5结构

                         Html
                         
                         <!DOCTYPE html>
    
我的第一个网页

网站标题

<main>
    <article>
        <h2>文章标题</h2>
        <p>这里是文章内容...</p>
    </article>
    
    <aside>
        <h3>相关链接</h3>
        <ul>
            <li><a href="#">链接1</a></li>
            <li><a href="#">链接2</a></li>
        </ul>
    </aside>
</main>

<footer>
    <p>&copy; 2025 我的网站</p>
</footer>
2. CSS3布局与响应式设计
                        Css
                        
                        /* 基础重置 */
  • { margin: 0; padding: 0; box-sizing: border-box; }

body { font-family: 'Arial', sans-serif; line-height: 1.6; color: #333; }

/* Flexbox布局 */ header { display: flex; justify-content: space-between; align-items: center; padding: 1rem; background-color: #2c3e50; color: white; }

nav ul { display: flex; list-style: none; }

nav li { margin-left: 1rem; }

nav a { color: white; text-decoration: none; }

/* 网格布局 */ main { display: grid; grid-template-columns: 2fr 1fr; gap: 2rem; padding: 2rem; }

/* 响应式设计 */ @media (max-width: 768px) { main { grid-template-columns: 1fr; }

header {
    flex-direction: column;
    text-align: center;
}

nav ul {
    margin-top: 1rem;
}

}

/* CSS3动画 */ button { padding: 0.5rem 1rem; background-color: #3498db; color: white; border: none; border-radius: 4px; cursor: pointer; transition: all 0.3s ease; }

button:hover { background-color: #2980b9; transform: translateY(-2px); box-shadow: 0 2px 5px rgba(0,0,0,0.2); }二、JavaScript核心技术与实战 JavaScript是Web前端开发的灵魂,以下是基础到进阶的核心知识点和代码示例:

  1. JavaScript基础语法

                         Javascript
                         
                         // 变量与数据类型
    

let name = "张三"; const age = 25; var isStudent = true; let scores = [90, 85, 78]; let person = { name: "李四", age: 30, hobbies: ["阅读", "编程"] };

// 函数定义与调用 function greet(person) { return 你好,${person.name}!你今年${person.age}岁。; }

console.log(greet(person));

// 条件语句 if (age >= 18) { console.log(${name}是成年人); } else { console.log(${name}是未成年人); }

// 循环语句 for (let i = 0; i < scores.length; i++) { console.log(第${i+1}次考试成绩: ${scores[i]}); }

scores.forEach((score, index) => { console.log(使用forEach: 第${index+1}次考试成绩: ${score}); });2. DOM操作与事件处理

                        Javascript
                        
                        // 获取DOM元素

const button = document.getElementById('myButton'); const output = document.querySelector('.output');

// 事件监听 button.addEventListener('click', function() { const randomNum = Math.floor(Math.random() * 100); output.textContent = 随机数: ${randomNum};

// 添加CSS类
this.classList.add('clicked');

// 创建新元素
const newElement = document.createElement('p');
newElement.textContent = `按钮被点击,生成随机数: ${randomNum}`;
document.body.appendChild(newElement);

});

// 表单处理 const form = document.querySelector('form'); form.addEventListener('submit', function(e) { e.preventDefault(); const input = document.querySelector('#username'); alert(欢迎, ${input.value}!); input.value = ''; });3. ES6+新特性

                        Javascript
                        
                        // 箭头函数

const add = (a, b) => a + b;

// 模板字符串 const intro = 我叫${name},今年${age}岁,是一名${isStudent ? '学生' : '职场人士'};

// 解构赋值 const { name: personName, age: personAge } = person; console.log(personName, personAge);

// 展开运算符 const newScores = [...scores, 95, 88]; console.log(newScores);

// Promise与异步编程 function fetchData(url) { return new Promise((resolve, reject) => { fetch(url) .then(response => response.json()) .then(data => resolve(data)) .catch(error => reject(error)); }); }

// async/await async function getData() { try { const data = await fetchData('api.example.com/data'); console.log(data); } catch (error) { console.error('获取数据失败:', error); } }三、前端框架Vue3实战 Vue3是目前最流行的前端框架之一,以下是核心概念和代码示例:

  1. Vue3基础

                         Html
                         
                         <!DOCTYPE html>
    
Vue3入门

{{ title }}

计数器: {{ count }}

增加 减少
    <input v-model="message" placeholder="输入消息">
    <p>你输入的是: {{ message }}</p>
    
    <ul>
        <li v-for="(item, index) in items" :key="index">
            {{ item.text }}
        </li>
    </ul>
</div>

<script>
    const { createApp, ref, reactive } = Vue;
    
    createApp({
        setup() {
            const title = ref('Vue3示例');
            const count = ref(0);
            const message = ref('');
            const items = reactive([
                { text: '学习Vue' },
                { text: '学习React' },
                { text: '学习Node.js' }
            ]);
            
            function increment() {
                count.value++;
            }
            
            function decrement() {
                count.value--;
            }
            
            return {
                title,
                count,
                message,
                items,
                increment,
                decrement
            };
        }
    }).mount('#app');
</script>
2. Vue3组件化开发
                        Html
                        
                        <!-- 父组件 -->
四、Node.js后端基础与全栈开发

Node.js让JavaScript可以用于后端开发,实现全栈能力:

  1. Express基础服务器

                         Javascript
                         
                         // server.js
    

const express = require('express'); const app = express(); const PORT = 3000;

// 中间件 app.use(express.json()); app.use(express.static('public'));

// 模拟数据库 let users = [ { id: 1, name: '张三', age: 25 }, { id: 2, name: '李四', age: 30 } ];

// RESTful API app.get('/api/users', (req, res) => { res.json(users); });

app.get('/api/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).send('用户未找到'); res.json(user); });

app.post('/api/users', (req, res) => { const user = { id: users.length + 1, name: req.body.name, age: req.body.age }; users.push(user); res.status(201).json(user); });

app.put('/api/users/:id', (req, res) => { const user = users.find(u => u.id === parseInt(req.params.id)); if (!user) return res.status(404).send('用户未找到');

user.name = req.body.name || user.name;
user.age = req.body.age || user.age;

res.json(user);

});

app.delete('/api/users/:id', (req, res) => { const userIndex = users.findIndex(u => u.id === parseInt(req.params.id)); if (userIndex === -1) return res.status(404).send('用户未找到');

users.splice(userIndex, 1);
res.status(204).send();

});

// 启动服务器 app.listen(PORT, () => { console.log(服务器运行在 http://localhost:${PORT}); });2. 前端与后端交互

                        Javascript
                        
                        // 前端使用fetch API与后端交互

async function fetchUsers() { try { const response = await fetch('/api/users'); if (!response.ok) throw new Error('获取用户数据失败'); const users = await response.json(); displayUsers(users); } catch (error) { console.error('Error:', error); } }

async function addUser(user) { try { const response = await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify(user) });

    if (!response.ok) throw new Error('添加用户失败');
    const newUser = await response.json();
    return newUser;
} catch (error) {
    console.error('Error:', error);
    throw error;
}

}

// 使用示例 document.querySelector('#userForm').addEventListener('submit', async (e) => { e.preventDefault(); const name = document.querySelector('#name').value; const age = document.querySelector('#age').value;

try {
    const newUser = await addUser({ name, age });
    console.log('新用户添加成功:', newUser);
    fetchUsers(); // 刷新用户列表
} catch (error) {
    alert('添加用户失败,请重试');
}

});

// 页面加载时获取用户列表 document.addEventListener('DOMContentLoaded', fetchUsers);五、实战项目:待办事项全栈应用

  1. 前端Vue组件

                         Html
                         
                         <!-- TodoApp.vue -->
    
.todo-app { max-width: 500px; margin: 0 auto; padding: 20px; font-family: Arial, sans-serif; } .todo-form { display: flex; margin-bottom: 20px; } .todo-form input { flex-grow: