当前位置: 首页 > article >正文

JavaScript网页设计案例:响应式动态购物车

       在现代网页开发中,购物车是电子商务网站的重要功能之一。通过JavaScript,我们可以实现一个响应式动态购物车,提供用户友好的体验,并展示前端开发的核心能力。


案例需求

我们的购物车需要实现以下功能:

  1. 动态添加商品:用户可以从商品列表中选择并添加商品到购物车。
  2. 实时更新:购物车的商品数量、价格和总金额自动更新。
  3. 修改商品数量:用户可以调整购物车中商品的数量。
  4. 移除商品:用户可以从购物车中移除商品。
  5. 结算功能:显示总金额并模拟提交订单。

HTML结构

首先,我们构建基本的HTML页面结构,包含商品展示区和购物车。

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>动态购物车</title>
    <link rel="stylesheet" href="styles.css">
</head>
<body>
    <div class="container">
        <h1>在线商店</h1>
        <div class="product-list">
            <div class="product" data-id="1" data-price="50">
                <h2>商品A</h2>
                <p>价格:$50</p>
                <button class="add-to-cart">添加到购物车</button>
            </div>
            <div class="product" data-id="2" data-price="100">
                <h2>商品B</h2>
                <p>价格:$100</p>
                <button class="add-to-cart">添加到购物车</button>
            </div>
            <div class="product" data-id="3" data-price="150">
                <h2>商品C</h2>
                <p>价格:$150</p>
                <button class="add-to-cart">添加到购物车</button>
            </div>
        </div>
        <div class="shopping-cart">
            <h2>购物车</h2>
            <ul id="cart-items"></ul>
            <p id="total-price">总金额:$0</p>
            <button id="checkout">结算</button>
        </div>
    </div>
    <script src="script.js"></script>
</body>
</html>

CSS样式

设计一个简洁的样式,使页面布局清晰且美观。

body {
    font-family: Arial, sans-serif;
    margin: 0;
    padding: 0;
    background-color: #f8f9fa;
    color: #333;
    display: flex;
    justify-content: center;
    align-items: center;
    height: 100vh;
}

.container {
    background: #ffffff;
    padding: 20px;
    border-radius: 5px;
    box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
    display: flex;
    gap: 20px;
}

.product-list, .shopping-cart {
    width: 50%;
}

.product {
    background: #f1f1f1;
    padding: 15px;
    border: 1px solid #ddd;
    border-radius: 4px;
    margin-bottom: 10px;
}

button {
    background-color: #007bff;
    color: #fff;
    border: none;
    border-radius: 4px;
    padding: 10px;
    cursor: pointer;
    transition: background-color 0.3s;
}

button:hover {
    background-color: #0056b3;
}

#cart-items {
    list-style: none;
    padding: 0;
}

#cart-items li {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

#total-price {
    font-size: 18px;
    font-weight: bold;
}

JavaScript功能实现

通过JavaScript,我们实现动态交互功能。

document.addEventListener('DOMContentLoaded', () => {
    const cartItems = document.getElementById('cart-items');
    const totalPrice = document.getElementById('total-price');
    const checkoutButton = document.getElementById('checkout');
    const addToCartButtons = document.querySelectorAll('.add-to-cart');

    let cart = [];

    // 添加商品到购物车
    addToCartButtons.forEach(button => {
        button.addEventListener('click', () => {
            const productElement = button.parentElement;
            const productId = productElement.getAttribute('data-id');
            const productName = productElement.querySelector('h2').textContent;
            const productPrice = parseFloat(productElement.getAttribute('data-price'));

            const existingProduct = cart.find(item => item.id === productId);

            if (existingProduct) {
                existingProduct.quantity += 1;
            } else {
                cart.push({ id: productId, name: productName, price: productPrice, quantity: 1 });
            }

            updateCartUI();
        });
    });

    // 更新购物车UI
    function updateCartUI() {
        cartItems.innerHTML = '';
        let total = 0;

        cart.forEach(item => {
            total += item.price * item.quantity;

            const cartItem = document.createElement('li');
            cartItem.innerHTML = `${item.name} - $${item.price} x ${item.quantity}
                <button class="remove-item" data-id="${item.id}">移除</button>`;

            cartItems.appendChild(cartItem);

            // 移除商品
            cartItem.querySelector('.remove-item').addEventListener('click', () => {
                cart = cart.filter(cartItem => cartItem.id !== item.id);
                updateCartUI();
            });
        });

        totalPrice.textContent = `总金额:$${total.toFixed(2)}`;
    }

    // 模拟结算
    checkoutButton.addEventListener('click', () => {
        if (cart.length === 0) {
            alert('购物车为空!');
            return;
        }

        alert(`订单已提交!总金额:$${cart.reduce((sum, item) => sum + item.price * item.quantity, 0).toFixed(2)}`);
        cart = [];
        updateCartUI();
    });
});

功能演示

  1. 商品添加:点击“添加到购物车”,商品立即显示在购物车列表中。
  2. 实时更新:购物车总金额自动更新,无需刷新页面。
  3. 数量修改:添加相同商品会增加数量。
  4. 商品移除:点击“移除”按钮即可删除商品。
  5. 订单提交:点击“结算”按钮,模拟提交订单。

总结

通过本案例,你学习了如何使用HTML、CSS和JavaScript构建一个功能完整的动态购物车。这个案例不仅展示了前端开发的基本技能,还可以作为更复杂的电子商务项目的起点。


http://www.kler.cn/a/471673.html

相关文章:

  • Python自学 - property装饰器(方法变成属性)
  • MySQL时提示,服务正在启动或者停止中,请稍候片刻后再试一次
  • 企业级Java 实体对象类定义规范
  • 汽车信息安全 -- S32K1如何更新BOOT_MAC
  • 【Java项目】基于SpringBoot的【垃圾分类系统】
  • Java爬虫获取淘宝关键字API接口:技术与应用指南
  • Rust编程语言
  • 141.环形链表 142.环形链表II
  • Azure主机windows2008就地升级十步
  • torch.max和torch.softmax python max
  • hpm使用笔记————使用usb作为从机接收来自上位机的数据然后通过spi主机发送给spi从机
  • 使用 PyTorch 自定义数据集并划分训练、验证与测试集
  • Mysql--基础篇--数据类型(整数,浮点数,日期,枚举,二进制,空间类型等)
  • Jupyter Markdown样式说明
  • HTML静态网页成品作业(HTML+CSS)——婚礼婚纱网页设计制作(6个页面)
  • OSPF使能配置
  • 攻防靶场(32):两个爆破技巧 Funbox 7 EasyEnum
  • 5. 多线程(3) --- synchronized
  • 力扣经典题目之2283. 判断一个数的数字计数是否等于数位的值
  • [网络安全]DVWA之File Upload—AntSword(蚁剑)攻击姿势及解题详析合集