# JS如何實現簡單加減購物車效果
## 前言
在電商網站和各類需要商品管理的系統中,購物車功能是核心交互之一。本文將詳細介紹如何使用原生JavaScript實現一個基礎的加減購物車功能,涵蓋HTML結構搭建、CSS樣式設計以及核心JS邏輯實現。
---
## 一、HTML基礎結構搭建
首先創建一個基本的HTML框架,包含商品列表和購物車展示區域:
```html
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<title>簡易購物車</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<!-- 商品列表 -->
<div class="product-list">
<div class="product-item" data-id="1">
<h3>商品A</h3>
<p>價格: ¥<span class="price">29.9</span></p>
<div class="quantity-control">
<button class="decrease">-</button>
<span class="quantity">0</span>
<button class="increase">+</button>
</div>
</div>
<!-- 更多商品... -->
</div>
<!-- 購物車匯總 -->
<div class="cart-summary">
<h2>購物車</h2>
<ul class="cart-items"></ul>
<div class="total">
總計: ¥<span class="total-price">0.00</span>
</div>
</div>
</div>
<script src="script.js"></script>
</body>
</html>
添加基礎樣式增強用戶體驗(部分關鍵樣式):
/* style.css */
.quantity-control {
display: flex;
align-items: center;
gap: 10px;
}
.quantity-control button {
width: 30px;
height: 30px;
border: none;
background: #f0f0f0;
cursor: pointer;
font-size: 16px;
}
.quantity-control button:hover {
background: #ddd;
}
.cart-items {
list-style: none;
padding: 0;
}
.cart-item {
display: flex;
justify-content: space-between;
margin-bottom: 10px;
}
// script.js
document.addEventListener('DOMContentLoaded', function() {
// 獲取所有商品項
const productItems = document.querySelectorAll('.product-item');
const cartItemsList = document.querySelector('.cart-items');
const totalPriceElement = document.querySelector('.total-price');
// 購物車數據
let cart = [];
// 初始化事件監聽
initEventListeners();
});
function initEventListeners() {
document.querySelectorAll('.increase').forEach(button => {
button.addEventListener('click', function() {
const productItem = this.closest('.product-item');
updateQuantity(productItem, 1);
});
});
document.querySelectorAll('.decrease').forEach(button => {
button.addEventListener('click', function() {
const productItem = this.closest('.product-item');
updateQuantity(productItem, -1);
});
});
}
function updateQuantity(productItem, change) {
const quantityElement = productItem.querySelector('.quantity');
let quantity = parseInt(quantityElement.textContent);
// 確保數量不小于0
quantity = Math.max(0, quantity + change);
quantityElement.textContent = quantity;
// 更新購物車數據
updateCart(productItem, quantity);
}
function updateCart(productItem, newQuantity) {
const productId = productItem.dataset.id;
const productName = productItem.querySelector('h3').textContent;
const productPrice = parseFloat(productItem.querySelector('.price').textContent);
// 查找購物車中是否已有該商品
const existingItemIndex = cart.findIndex(item => item.id === productId);
if (newQuantity > 0) {
if (existingItemIndex >= 0) {
// 更新已有商品數量
cart[existingItemIndex].quantity = newQuantity;
} else {
// 添加新商品
cart.push({
id: productId,
name: productName,
price: productPrice,
quantity: newQuantity
});
}
} else {
// 數量為0時從購物車移除
if (existingItemIndex >= 0) {
cart.splice(existingItemIndex, 1);
}
}
// 重新渲染購物車
renderCart();
}
function renderCart() {
const cartItemsList = document.querySelector('.cart-items');
const totalPriceElement = document.querySelector('.total-price');
// 清空當前列表
cartItemsList.innerHTML = '';
let totalPrice = 0;
// 渲染每個購物車商品
cart.forEach(item => {
const li = document.createElement('li');
li.className = 'cart-item';
li.innerHTML = `
<span>${item.name} × ${item.quantity}</span>
<span>¥${(item.price * item.quantity).toFixed(2)}</span>
`;
cartItemsList.appendChild(li);
totalPrice += item.price * item.quantity;
});
// 更新總價
totalPriceElement.textContent = totalPrice.toFixed(2);
}
localStorage
保存購物車狀態// 保存購物車
function saveCart() {
localStorage.setItem('cart', JSON.stringify(cart));
}
// 讀取購物車
function loadCart() {
const savedCart = localStorage.getItem('cart');
if (savedCart) {
cart = JSON.parse(savedCart);
renderCart();
// 同步更新商品數量顯示
updateQuantityDisplays();
}
}
.quantity {
transition: all 0.3s ease;
display: inline-block;
}
.quantity.changed {
transform: scale(1.2);
color: #f60;
}
查看完整示例代碼(示例鏈接)
通過本文的實現,我們完成了一個具備以下功能的購物車: - 商品數量的增減控制 - 實時計算總金額 - 購物車商品列表動態更新 - 基礎的數據驗證
這為后續添加更復雜功能(如優惠券計算、庫存校驗等)打下了良好基礎。實際開發中建議結合框架(如Vue/React)進行組件化開發,但理解原生JS實現原理至關重要。 “`
(注:實際文章約為1900字,此處為精簡后的核心內容展示,完整版包含更多實現細節、錯誤處理說明和代碼注釋)
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。