这份代码包含了三个核心页面,并采用了模块化的设计,方便您进行修改和扩展:

HTML图书类网页设计源代码
(图片来源网络,侵删)
  1. 首页:展示图书列表、搜索功能和分类筛选。
  2. 图书详情页:展示单本图书的详细信息、内容简介和读者评论。
  3. 购物车页面:展示已选图书,支持修改数量和结算。

技术栈

  • HTML5: 语义化标签构建页面结构。
  • CSS3: 使用Flexbox和Grid布局,实现响应式设计。
  • JavaScript (原生): 实现交互功能,如搜索、筛选、购物车管理等。
  • Font Awesome: 提供高质量的图标。

项目结构

为了保持代码的整洁,我们建议将文件按以下结构组织:

bookstore/
├── index.html          # 首页
├── book-detail.html    # 图书详情页
├── cart.html           # 购物车页面
├── css/
│   └── style.css      # 全局样式表
└── js/
    └── script.js      # 全局JavaScript脚本

首页 (index.html)

这是用户进入网站时看到的第一个页面,展示了图书的核心功能。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">云端书库 - 您的线上书店</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <!-- 导航栏 -->
    <header class="main-header">
        <div class="container">
            <a href="index.html" class="logo">云端书库</a>
            <nav class="main-nav">
                <a href="index.html">首页</a>
                <a href="#">分类</a>
                <a href="#">新书推荐</a>
                <a href="#">关于我们</a>
            </nav>
            <div class="header-actions">
                <a href="cart.html" class="cart-btn">
                    <i class="fas fa-shopping-cart"></i>
                    <span class="cart-count">0</span>
                </a>
                <a href="#" class="user-btn"><i class="fas fa-user"></i></a>
            </div>
        </div>
    </header>
    <main>
        <!-- 搜索和筛选区 -->
        <section class="search-filter-section container">
            <div class="search-bar">
                <input type="text" id="search-input" placeholder="搜索书名、作者或ISBN...">
                <button id="search-btn"><i class="fas fa-search"></i></button>
            </div>
            <div class="filter-bar">
                <span>分类筛选:</span>
                <div class="filter-options">
                    <button class="filter-btn active" data-category="all">全部</button>
                    <button class="filter-btn" data-category="fiction">小说</button>
                    <button class="filter-btn" data-category="tech">科技</button>
                    <button class="filter-btn" data-category="history">历史</button>
                    <button class="filter-btn" data-category="art">艺术</button>
                </div>
            </div>
        </section>
        <!-- 图书列表 -->
        <section class="book-list-section container">
            <h2>热门图书</h2>
            <div class="book-grid" id="book-grid">
                <!-- 图书项目将通过JavaScript动态生成 -->
                <!-- 示例图书项目 (实际开发中应从JS生成) -->
                <div class="book-item" data-category="fiction" data-title="三体" data-author="刘慈欣">
                    <img src="https://via.placeholder.com/200x300.png?text=三体" alt="三体封面">
                    <div class="book-info">
                        <h3>三体</h3>
                        <p class="author">刘慈欣</p>
                        <p class="price">¥45.00</p>
                        <button class="add-to-cart-btn">加入购物车</button>
                    </div>
                </div>
                 <div class="book-item" data-category="tech" data-title="JavaScript高级程序设计" data-author="Nicholas C. Zakas">
                    <img src="https://via.placeholder.com/200x300.png?text=JS高级" alt="JS高级程序设计封面">
                    <div class="book-info">
                        <h3>JavaScript高级程序设计</h3>
                        <p class="author">Nicholas C. Zakas</p>
                        <p class="price">¥99.00</p>
                        <button class="add-to-cart-btn">加入购物车</button>
                    </div>
                </div>
            </div>
        </section>
    </main>
    <!-- 页脚 -->
    <footer class="main-footer">
        <div class="container">
            <p>&copy; 2025 云端书库. 保留所有权利.</p>
        </div>
    </footer>
    <script src="js/script.js"></script>
</body>
</html>

图书详情页 (book-detail.html)

点击某本图书后跳转至此页面,展示更丰富的信息。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">图书详情 - 云端书库</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <style>
        /* 详情页特有样式 */
        .book-detail {
            display: flex;
            gap: 40px;
            margin-top: 20px;
        }
        .book-detail-image {
            flex: 0 0 300px;
        }
        .book-detail-image img {
            width: 100%;
            border-radius: 8px;
            box-shadow: 0 4px 15px rgba(0,0,0,0.1);
        }
        .book-detail-info {
            flex: 1;
        }
        .book-detail-info h1 {
            font-size: 2.5em;
            margin-bottom: 10px;
        }
        .book-meta {
            color: #666;
            margin-bottom: 20px;
        }
        .book-description {
            line-height: 1.8;
            margin-bottom: 30px;
        }
        .book-actions {
            display: flex;
            align-items: center;
            gap: 20px;
        }
        .book-actions .price {
            font-size: 2em;
            font-weight: bold;
            color: #e74c3c;
        }
        .book-actions .add-to-cart-btn {
            padding: 12px 30px;
            font-size: 1.1em;
        }
        .reviews-section {
            margin-top: 50px;
            border-top: 1px solid #eee;
            padding-top: 30px;
        }
        .review-item {
            background-color: #f9f9f9;
            padding: 20px;
            border-radius: 8px;
            margin-bottom: 15px;
        }
    </style>
</head>
<body>
    <!-- 导航栏 (与首页共用,实际项目中可用模板引擎或JS包含) -->
    <header class="main-header">
        <div class="container">
            <a href="index.html" class="logo">云端书库</a>
            <nav class="main-nav">
                <a href="index.html">首页</a>
                <a href="#">分类</a>
                <a href="#">新书推荐</a>
                <a href="#">关于我们</a>
            </nav>
            <div class="header-actions">
                <a href="cart.html" class="cart-btn">
                    <i class="fas fa-shopping-cart"></i>
                    <span class="cart-count">0</span>
                </a>
                <a href="#" class="user-btn"><i class="fas fa-user"></i></a>
            </div>
        </div>
    </header>
    <main class="container">
        <div class="book-detail">
            <div class="book-detail-image">
                <img src="https://via.placeholder.com/300x450.png?text=三体" alt="三体封面大图">
            </div>
            <div class="book-detail-info">
                <h1>三体</h1>
                <div class="book-meta">
                    <p><strong>作者:</strong>刘慈欣</p>
                    <p><strong>出版社:</strong>重庆出版社</p>
                    <p><strong>ISBN:</strong>9787536692930</p>
                    <p><strong>出版时间:</strong>2008年1月</p>
                </div>
                <p class="book-description">
                    文化大革命如火如荼进行的同时,军方探寻外星文明的绝秘计划“红岸工程”取得了突破性进展,但在按下发射键的那一刻,历史没有如预想的那样继续演进,四光年外,“三体文明”正苦于三颗无规则运行的太阳所带来的极端气候,急于寻找新的家园,在运用超技术锁死地球人的基础科学之后,庞大的三体舰队开始向地球进发,人类的末日悄然来临...
                </p>
                <div class="book-actions">
                    <span class="price">¥45.00</span>
                    <button class="add-to-cart-btn">加入购物车</button>
                </div>
            </div>
        </div>
        <section class="reviews-section">
            <h2>读者评论</h2>
            <div class="review-item">
                <div class="review-header">
                    <strong>读者A</strong>
                    <span class="rating">★★★★★</span>
                </div>
                <p>一部里程碑式的科幻巨作,想象力天马行空,逻辑严密,震撼人心!</p>
            </div>
            <div class="review-item">
                <div class="review-header">
                    <strong>读者B</strong>
                    <span class="rating">★★★★☆</span>
                </div>
                <p>宏大的世界观和深刻的哲学思考,虽然有些地方略显晦涩,但瑕不掩瑜。</p>
            </div>
        </section>
    </main>
    <!-- 页脚 (与首页共用) -->
    <footer class="main-footer">
        <div class="container">
            <p>&copy; 2025 云端书库. 保留所有权利.</p>
        </div>
    </footer>
    <script src="js/script.js"></script>
</body>
</html>

购物车页面 (cart.html)

管理用户已选择的图书。

<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">购物车 - 云端书库</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0-beta3/css/all.min.css">
    <link rel="stylesheet" href="css/style.css">
    <style>
        /* 购物车特有样式 */
        .cart-section {
            margin-top: 20px;
        }
        .cart-table {
            width: 100%;
            border-collapse: collapse;
        }
        .cart-table th, .cart-table td {
            padding: 15px;
            text-align: left;
            border-bottom: 1px solid #ddd;
        }
        .cart-table th {
            background-color: #f8f9fa;
            font-weight: bold;
        }
        .cart-item-image {
            width: 80px;
            height: 120px;
            object-fit: cover;
        }
        .cart-item-info {
            flex: 1;
        }
        .cart-item-title {
            font-weight: bold;
            margin-bottom: 5px;
        }
        .cart-item-author {
            color: #666;
            font-size: 0.9em;
        }
        .quantity-control {
            display: flex;
            align-items: center;
            gap: 10px;
        }
        .quantity-btn {
            width: 30px;
            height: 30px;
            border: 1px solid #ccc;
            background-color: #f8f9fa;
            border-radius: 4px;
            cursor: pointer;
        }
        .quantity-input {
            width: 50px;
            text-align: center;
            border: 1px solid #ccc;
            border-radius: 4px;
            padding: 5px;
        }
        .cart-summary {
            margin-top: 30px;
            text-align: right;
        }
        .summary-row {
            display: flex;
            justify-content: space-between;
            margin-bottom: 10px;
        }
        .summary-row.total {
            font-size: 1.5em;
            font-weight: bold;
            margin-top: 20px;
            padding-top: 20px;
            border-top: 2px solid #333;
        }
        .checkout-btn {
            margin-top: 20px;
            padding: 15px 40px;
            font-size: 1.2em;
            background-color: #2ecc71;
            color: white;
            border: none;
            border-radius: 5px;
            cursor: pointer;
            transition: background-color 0.3s;
        }
        .checkout-btn:hover {
            background-color: #27ae60;
        }
        .empty-cart-message {
            text-align: center;
            padding: 50px;
            color: #999;
        }
    </style>
</head>
<body>
    <!-- 导航栏 (与首页共用) -->
    <header class="main-header">
        <div class="container">
            <a href="index.html" class="logo">云端书库</a>
            <nav class="main-nav">
                <a href="index.html">首页</a>
                <a href="#">分类</a>
                <a href="#">新书推荐</a>
                <a href="#">关于我们</a>
            </nav>
            <div class="header-actions">
                <a href="cart.html" class="cart-btn">
                    <i class="fas fa-shopping-cart"></i>
                    <span class="cart-count">0</span>
                </a>
                <a href="#" class="user-btn"><i class="fas fa-user"></i></a>
            </div>
        </div>
    </header>
    <main class="container">
        <h1>我的购物车</h1>
        <section class="cart-section">
            <div id="cart-items-container">
                <!-- 购物车内容将通过JavaScript动态生成 -->
                <div class="empty-cart-message">
                    <i class="fas fa-shopping-cart" style="font-size: 3em; margin-bottom: 20px;"></i>
                    <p>您的购物车是空的,快去挑选心仪的图书吧!</p>
                    <a href="index.html" class="btn">去逛逛</a>
                </div>
            </div>
            <div class="cart-summary" id="cart-summary" style="display: none;">
                <div class="summary-row">
                    <span>商品总计:</span>
                    <span id="subtotal">¥0.00</span>
                </div>
                <div class="summary-row">
                    <span>运费:</span>
                    <span id="shipping">¥10.00</span>
                </div>
                <div class="summary-row total">
                    <span>总计:</span>
                    <span id="total-price">¥0.00</span>
                </div>
                <button class="checkout-btn">立即结算</button>
            </div>
        </section>
    </main>
    <!-- 页脚 (与首页共用) -->
    <footer class="main-footer">
        <div class="container">
            <p>&copy; 2025 云端书库. 保留所有权利.</p>
        </div>
    </footer>
    <script src="js/script.js"></script>
</body>
</html>

CSS 样式表 (css/style.css)

这是整个网站的视觉样式定义。

/* 全局重置和基础样式 */
* {
    margin: 0;
    padding: 0;
    box-sizing: border-box;
}
body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
    line-height: 1.6;
    color: #333;
    background-color: #f4f4f4;
}
.container {
    max-width: 1200px;
    margin: 0 auto;
    padding: 0 20px;
}
a {
    text-decoration: none;
    color: #007bff;
}
ul {
    list-style: none;
}
img {
    max-width: 100%;
}
/* 按钮通用样式 */
.btn {
    display: inline-block;
    padding: 10px 20px;
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}
.btn:hover {
    background-color: #0056b3;
}
/* 导航栏 */
.main-header {
    background-color: #fff;
    box-shadow: 0 2px 5px rgba(0,0,0,0.1);
    position: sticky;
    top: 0;
    z-index: 1000;
}
.main-header .container {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 15px 20px;
}
.logo {
    font-size: 1.8em;
    font-weight: bold;
    color: #333;
}
.main-nav a {
    color: #333;
    margin-left: 20px;
    font-weight: 500;
}
.main-nav a:hover {
    color: #007bff;
}
.header-actions {
    display: flex;
    align-items: center;
}
.cart-btn, .user-btn {
    position: relative;
    font-size: 1.2em;
    color: #333;
    margin-left: 20px;
}
.cart-count {
    position: absolute;
    top: -8px;
    right: -8px;
    background-color: #e74c3c;
    color: white;
    border-radius: 50%;
    width: 20px;
    height: 20px;
    display: flex;
    align-items: center;
    justify-content: center;
    font-size: 0.7em;
    font-weight: bold;
}
/* 图书列表区 */
.search-filter-section {
    background-color: #fff;
    padding: 20px;
    margin: 20px auto;
    border-radius: 8px;
    box-shadow: 0 2px 5px rgba(0,0,0,0.05);
}
.search-bar {
    display: flex;
    margin-bottom: 20px;
}
.search-bar input {
    flex: 1;
    padding: 12px;
    border: 1px solid #ddd;
    border-radius: 5px 0 0 5px;
    font-size: 1em;
}
.search-bar button {
    padding: 12px 20px;
    border: 1px solid #007bff;
    background-color: #007bff;
    color: white;
    border-radius: 0 5px 5px 0;
    cursor: pointer;
}
.filter-bar {
    display: flex;
    align-items: center;
    gap: 15px;
}
.filter-options {
    display: flex;
    gap: 10px;
}
.filter-btn {
    padding: 8px 15px;
    border: 1px solid #ddd;
    background-color: #fff;
    border-radius: 20px;
    cursor: pointer;
    transition: all 0.3s ease;
}
.filter-btn:hover, .filter-btn.active {
    background-color: #007bff;
    color: white;
    border-color: #007bff;
}
/* 图书网格 */
.book-list-section h2 {
    margin-bottom: 20px;
    color: #333;
}
.book-grid {
    display: grid;
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 30px;
}
.book-item {
    background-color: #fff;
    border-radius: 8px;
    overflow: hidden;
    box-shadow: 0 4px 10px rgba(0,0,0,0.1);
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    cursor: pointer;
}
.book-item:hover {
    transform: translateY(-5px);
    box-shadow: 0 8px 20px rgba(0,0,0,0.15);
}
.book-item img {
    width: 100%;
    height: 300px;
    object-fit: cover;
}
.book-info {
    padding: 15px;
}
.book-info h3 {
    font-size: 1.1em;
    margin-bottom: 8px;
    white-space: nowrap;
    overflow: hidden;
    text-overflow: ellipsis;
}
.book-info .author {
    color: #666;
    font-size: 0.9em;
    margin-bottom: 10px;
}
.book-info .price {
    font-weight: bold;
    color: #e74c3c;
    font-size: 1.2em;
    margin-bottom: 15px;
}
.add-to-cart-btn {
    width: 100%;
    padding: 10px;
    border: none;
    background-color: #2ecc71;
    color: white;
    border-radius: 5px;
    cursor: pointer;
    font-weight: bold;
    transition: background-color 0.3s ease;
}
.add-to-cart-btn:hover {
    background-color: #27ae60;
}
/* 页脚 */
.main-footer {
    background-color: #333;
    color: #ccc;
    text-align: center;
    padding: 20px 0;
    margin-top: 50px;
}

JavaScript 脚本 (js/script.js)

这是网站的“大脑”,负责所有动态交互。

document.addEventListener('DOMContentLoaded', () => {
    // --- 购物车功能 ---
    let cart = JSON.parse(localStorage.getItem('cart')) || [];
    // 更新购物车数量和显示
    function updateCartUI() {
        const cartCount = document.querySelector('.cart-count');
        const cartCountValue = cart.reduce((total, item) => total + item.quantity, 0);
        cartCount.textContent = cartCountValue;
        renderCartItems();
    }
    // 将商品添加到购物车
    function addToCart(book) {
        const existingItem = cart.find(item => item.id === book.id);
        if (existingItem) {
            existingItem.quantity++;
        } else {
            cart.push({ ...book, quantity: 1 });
        }
        localStorage.setItem('cart', JSON.stringify(cart));
        updateCartUI();
        alert(`《${book.title}》已添加到购物车!`);
    }
    // 渲染购物车列表
    function renderCartItems() {
        const container = document.getElementById('cart-items-container');
        const summarySection = document.getElementById('cart-summary');
        if (cart.length === 0) {
            container.innerHTML = `
                <div class="empty-cart-message">
                    <i class="fas fa-shopping-cart" style="font-size: 3em; margin-bottom: 20px;"></i>
                    <p>您的购物车是空的,快去挑选心仪的图书吧!</p>
                    <a href="index.html" class="btn">去逛逛</a>
                </div>
            `;
            summarySection.style.display = 'none';
            return;
        }
        summarySection.style.display = 'block';
        let html = '';
        let subtotal = 0;
        cart.forEach(item => {
            const itemTotal = item.price * item.quantity;
            subtotal += itemTotal;
            html += `
                <table class="cart-table">
                    <tbody>
                        <tr>
                            <td><img src="${item.image}" alt="${item.title}" class="cart-item-image"></td>
                            <td class="cart-item-info">
                                <div class="cart-item-title">${item.title}</div>
                                <div class="cart-item-author">作者:${item.author}</div>
                            </td>
                            <td>¥${item.price.toFixed(2)}</td>
                            <td>
                                <div class="quantity-control">
                                    <button class="quantity-btn" onclick="updateQuantity('${item.id}', -1)">-</button>
                                    <input type="number" class="quantity-input" value="${item.quantity}" onchange="setQuantity('${item.id}', this.value)" min="1">
                                    <button class="quantity-btn" onclick="updateQuantity('${item.id}', 1)">+</button>
                                </div>
                            </td>
                            <td>¥${itemTotal.toFixed(2)}</td>
                            <td><button class="remove-btn" onclick="removeFromCart('${item.id}')"><i class="fas fa-trash"></i></button></td>
                        </tr>
                    </tbody>
                </table>
            `;
        });
        container.innerHTML = html;
        // 更新总价
        const shipping = subtotal > 0 ? 10 : 0; // 满50包邮,这里简化为固定运费
        const total = subtotal + shipping;
        document.getElementById('subtotal').textContent = `¥${subtotal.toFixed(2)}`;
        document.getElementById('shipping').textContent = shipping === 0 ? '免运费' : `¥${shipping.toFixed(2)}`;
        document.getElementById('total-price').textContent = `¥${total.toFixed(2)}`;
    }
    // 全局函数,供HTML调用
    window.updateQuantity = function(id, change) {
        const item = cart.find(i => i.id === id);
        if (item) {
            item.quantity += change;
            if (item.quantity < 1) item.quantity = 1;
            localStorage.setItem('cart', JSON.stringify(cart));
            updateCartUI();
        }
    };
    window.setQuantity = function(id, value) {
        const item = cart.find(i => i.id === id);
        if (item) {
            item.quantity = parseInt(value) || 1;
            localStorage.setItem('cart', JSON.stringify(cart));
            updateCartUI();
        }
    };
    window.removeFromCart = function(id) {
        cart = cart.filter(item => item.id !== id);
        localStorage.setItem('cart', JSON.stringify(cart));
        updateCartUI();
    };
    // --- 首页功能 ---
    const bookGrid = document.getElementById('book-grid');
    const searchInput = document.getElementById('search-input');
    const searchBtn = document.getElementById('search-btn');
    const filterBtns = document.querySelectorAll('.filter-btn');
    // 模拟图书数据
    const booksData = [
        { id: '1', title: '三体', author: '刘慈欣', price: 45.00, category: 'fiction', image: 'https://via.placeholder.com/200x300.png?text=三体' },
        { id: '2', title: 'JavaScript高级程序设计', author: 'Nicholas C. Zakas', price: 99.00, category: 'tech', image: 'https://via.placeholder.com/200x300.png?text=JS高级' },
        { id: '3', title: '明朝那些事儿', author: '当年明月', price: 35.50, category: 'history', image: 'https://via.placeholder.com/200x300.png?text=明朝' },
        { id: '4', title: '艺术的故事', author: 'E.H.贡布里希', price: 280.00, category: 'art', image: 'https://via.placeholder.com/200x300.png?text=艺术' },
        { id: '5', title: '流浪地球', author: '刘慈欣', price: 28.00, category: 'fiction', image: 'https://via.placeholder.com/200x300.png?text=流浪地球' },
        { id: '6', title: '深入理解计算机系统', author: 'Randal E.Bryant', price: 139.00, category: 'tech', image: 'https://via.placeholder.com/200x300.png?text=CSAPP' },
    ];
    // 渲染图书列表
    function renderBooks(books) {
        bookGrid.innerHTML = '';
        books.forEach(book => {
            const bookElement = document.createElement('div');
            bookElement.className = 'book-item';
            bookElement.setAttribute('data-category', book.category);
            bookElement.setAttribute('data-title', book.title);
            bookElement.setAttribute('data-author', book.author);
            bookElement.innerHTML = `
                <img src="${book.image}" alt="${book.title}封面">
                <div class="book-info">
                    <h3>${book.title}</h3>
                    <p class="author">${book.author}</p>
                    <p class="price">¥${book.price.toFixed(2)}</p>
                    <button class="add-to-cart-btn" data-id="${book.id}" data-title="${book.title}" data-author="${book.author}" data-price="${book.price}" data-image="${book.image}">加入购物车</button>
                </div>
            `;
            bookGrid.appendChild(bookElement);
        });
        // 为新渲染的按钮添加事件监听器
        document.querySelectorAll('.add-to-cart-btn').forEach(btn => {
            btn.addEventListener('click', (e) => {
                const book = {
                    id: e.target.getAttribute('data-id'),
                    title: e.target.getAttribute('data-title'),
                    author: e.target.getAttribute('data-author'),
                    price: parseFloat(e.target.getAttribute('data-price')),
                    image: e.target.getAttribute('data-image')
                };
                addToCart(book);
            });
        });
    }
    // 搜索功能
    function performSearch() {
        const searchTerm = searchInput.value.toLowerCase();
        const filteredBooks = booksData.filter(book => 
            book.title.toLowerCase().includes(searchTerm) ||
            book.author.toLowerCase().includes(searchTerm)
        );
        renderBooks(filteredBooks);
    }
    // 筛选功能
    function performFilter(category) {
        if (category === 'all') {
            renderBooks(booksData);
        } else {
            const filteredBooks = booksData.filter(book => book.category === category);
            renderBooks(filteredBooks);
        }
    }
    // 事件监听器
    searchBtn.addEventListener('click', performSearch);
    searchInput.addEventListener('keyup', (e) => {
        if (e.key === 'Enter') {
            performSearch();
        }
    });
    filterBtns.forEach(btn => {
        btn.addEventListener('click', (e) => {
            filterBtns.forEach(b => b.classList.remove('active'));
            e.target.classList.add('active');
            performFilter(e.target.getAttribute('data-category'));
        });
    });
    // 初始化页面
    renderBooks(booksData);
    updateCartUI();
});

如何使用

  1. 创建文件夹和文件:按照上面的项目结构创建所有文件和文件夹。
  2. 复制代码:将对应的HTML、CSS和JavaScript代码分别复制到相应的文件中。
  3. 打开网页:用浏览器打开 index.html 文件,即可看到网站首页。

功能说明

  • 响应式设计:CSS使用了Flexbox和Grid,可以很好地适配不同屏幕尺寸。
  • 购物车持久化:使用 localStorage 保存购物车数据,即使用户刷新页面或关闭浏览器,购物车内容也不会丢失。
  • 动态交互
    • 点击“加入购物车”按钮,商品会添加到购物车,并更新页面上的购物车数量徽章。
    • 在购物车页面,可以增减商品数量或删除商品,总价会实时更新。
    • 首页的搜索和筛选功能可以动态过滤显示的图书列表。
  • 模块化:代码结构清晰,HTML负责结构,CSS负责样式,JavaScript负责行为,易于维护和扩展。

扩展建议

  • 后端集成:将静态的 booksData 替换为从服务器API获取数据。
  • 用户认证:添加登录/注册功能,将购物车与用户账户关联。
  • 订单系统:创建订单页面,实现下单和支付流程。
  • 分页:当图书数量很多时,为图书列表添加分页功能。
  • 更丰富的UI:添加加载动画、提示信息(Toast)等,提升用户体验。

这份源代码为您提供了一个功能完备的起点,您可以在此基础上进行二次开发,打造出功能更加强大的在线图书商城。