购物车(HTML+JS+CSS)

上图!!!

HTML源码

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>
  <link rel="stylesheet" href="static/css/购物车.css">
</head>
<body>

<div class="cart-container">
  <div class="cart-header">🛒 购物车</div>

  <table class="cart-table">
    <thead>
      <tr>
        <th class="col-check">
          <input type="checkbox" id="selectAll" title="全选">
        </th>
        <th class="col-product">商品</th>
        <th class="col-price">单价</th>
        <th class="col-qty">数量</th>
        <th class="col-subtotal">小计</th>
        <th class="col-action">操作</th>
      </tr>
    </thead>
    <tbody id="cartBody">
      <!-- JS 动态渲染 -->
    </tbody>
  </table>

  <!-- 底部结算栏 -->
  <div class="cart-footer">
    <div class="footer-left">
      <label class="select-all-label">
        <input type="checkbox" id="selectAllBottom"> 全选
      </label>
      <span class="selected-info" id="selectedInfo">已选 0 件商品</span>
    </div>
    <div class="footer-right">
      <div class="total-amount">
        <span class="total-label">总计:</span>
        <span class="total-price" id="totalPrice">¥0</span>
      </div>
      <button class="btn-checkout" id="btnCheckout">结算</button>
    </div>
  </div>
</div>

<script>
// ==================== 购物车逻辑 ====================

// 默认商品数据
const defaultData = [
  { id: 1, name: 'iPhone 15',  price: 5999, qty: 1, checked: true,  icon: '📱' },
  { id: 2, name: 'AirPods',   price: 1299, qty: 2, checked: true,  icon: '🎧' },
  { id: 3, name: 'MacBook Pro', price: 14999, qty: 1, checked: false, icon: '💻' },
  { id: 4, name: 'iPad Air',   price: 4799, qty: 1, checked: false, icon: '📋' },
];

// 从 localStorage 读取,没有则用默认数据
const STORAGE_KEY = 'cart_data';
let cartData = JSON.parse(localStorage.getItem(STORAGE_KEY)) || defaultData;

// ==================== DOM 引用 ====================
const cartBody    = document.getElementById('cartBody');
const selectAll  = document.getElementById('selectAll');
const selectAllBottom = document.getElementById('selectAllBottom');
const selectedInfo = document.getElementById('selectedInfo');
const totalPriceEl = document.getElementById('totalPrice');
const btnCheckout = document.getElementById('btnCheckout');

// ==================== 工具函数 ====================
const formatMoney = (n) => `¥${n.toLocaleString()}`;

function calcTotal() {
  const { count, sum } = cartData.reduce(
    (acc, item) => {
      if (item.checked) {
        acc.count += item.qty;
        acc.sum += item.price * item.qty;
      }
      return acc;
    },
    { count: 0, sum: 0 }
  );
  selectedInfo.textContent = `已选 ${count} 件商品`;
  totalPriceEl.textContent = formatMoney(sum);
}

function syncSelectAll() {
  const allChecked = cartData.length > 0 && cartData.every(item => item.checked);
  selectAll.checked = allChecked;
  selectAllBottom.checked = allChecked;
}

function saveToStorage() {
  localStorage.setItem(STORAGE_KEY, JSON.stringify(cartData));
}

function refreshUI() {
  calcTotal();
  syncSelectAll();
  saveToStorage();
}

// ==================== 渲染 ====================
function render() {
  if (cartData.length === 0) {
    cartBody.innerHTML = `
      <tr>
        <td colspan="6">
          <div class="empty-cart">
            <span class="empty-icon">🛒</span>
            购物车是空的,去逛逛吧~
          </div>
        </td>
      </tr>`;
  } else {
    cartBody.innerHTML = cartData
      .map(
        ({ id, name, price, qty, checked, icon }) => `
        <tr data-id="${id}">
          <td class="cell-check">
            <input type="checkbox" class="item-check" ${checked ? 'checked' : ''}>
          </td>
          <td>
            <div class="product-info">
              <div class="product-img">${icon}</div>
              <span class="product-name">${name}</span>
            </div>
          </td>
          <td class="cell-price">${formatMoney(price)}</td>
          <td>
            <div class="quantity-control">
              <button class="qty-btn btn-minus" ${qty <= 1 ? 'disabled' : ''}>−</button>
              <input type="number" class="qty-input" value="${qty}" min="1" readonly>
              <button class="qty-btn btn-plus">+</button>
            </div>
          </td>
          <td class="cell-subtotal">${formatMoney(price * qty)}</td>
          <td style="text-align:center">
            <button class="btn-delete">删除</button>
          </td>
        </tr>`
      )
      .join('');
  }
  refreshUI();
}

// ==================== 事件委托(给 tbody 绑定一个事件处理所有按钮) ====================
cartBody.addEventListener('click', (e) => {
  const btn = e.target;
  const row = btn.closest('tr');
  if (!row) return;
  const id = +row.dataset.id;
  const item = cartData.find(p => p.id === id);
  if (!item) return;

  // --- 减号按钮 ---
  if (btn.classList.contains('btn-minus')) {
    if (item.qty > 1) {
      item.qty--;
      render();
    }
  }

  // --- 加号按钮 ---
  if (btn.classList.contains('btn-plus')) {
    item.qty++;
    render();
  }

  // --- 删除按钮 ---
  if (btn.classList.contains('btn-delete')) {
    cartData = cartData.filter(p => p.id !== id);
    render();
  }

  // --- 单个商品勾选 ---
  if (btn.classList.contains('item-check')) {
    item.checked = btn.checked;
    refreshUI();
  }
});

// ==================== 全选 / 取消全选 ---
function handleSelectAll(e) {
  const checked = e.target.checked;
  cartData.forEach(item => (item.checked = checked));
  render();
}

selectAll.addEventListener('change', handleSelectAll);
selectAllBottom.addEventListener('change', handleSelectAll);

// ==================== 结算按钮 ====================
btnCheckout.addEventListener('click', () => {
  const selected = cartData.filter(item => item.checked);
  if (selected.length === 0) {
    alert('请先选择要结算的商品!');
    return;
  }
  const result = selected.map(({ id, name, price, qty }) => ({
    id,
    name,
    price,
    qty,
    subtotal: price * qty,
  }));
  console.log('结算商品(JSON):', JSON.stringify(result, null, 2));
  console.table(result);
  alert(`已选中 ${selected.length} 件商品,详情已输出到控制台`);
});

// ==================== 初始化 ====================
render();
</script>

</body>
</html>

CSS源码

css 复制代码
/* ========== 购物车样式 ========== */
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}

body {
  font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", "PingFang SC",
    "Hiragino Sans GB", "Microsoft YaHei", sans-serif;
  background: #f5f6f8;
  min-height: 100vh;
  display: flex;
  justify-content: center;
  padding: 40px 20px;
}

.cart-container {
  width: 880px;
  background: #fff;
  border-radius: 12px;
  box-shadow: 0 2px 16px rgba(0, 0, 0, 0.08);
  overflow: hidden;
}

/* 标题栏 */
.cart-header {
  padding: 24px 28px 0;
  font-size: 22px;
  font-weight: 700;
  color: #1a1a2e;
  border-bottom: 1px solid #eee;
  padding-bottom: 18px;
}

/* 表格 */
.cart-table {
  width: 100%;
  border-collapse: collapse;
}

.cart-table thead th {
  padding: 14px 16px;
  text-align: left;
  font-size: 13px;
  font-weight: 600;
  color: #888;
  background: #fafbfc;
  border-bottom: 1px solid #eee;
  white-space: nowrap;
}

.cart-table thead th.col-check {
  width: 60px;
  text-align: center;
}
.cart-table thead th.col-product {
  width: auto;
}
.cart-table thead th.col-price {
  width: 120px;
}
.cart-table thead th.col-qty {
  width: 150px;
  text-align: center;
}
.cart-table thead th.col-subtotal {
  width: 120px;
}
.cart-table thead th.col-action {
  width: 80px;
  text-align: center;
}

.cart-table tbody td {
  padding: 16px;
  vertical-align: middle;
  border-bottom: 1px solid #f0f0f0;
  font-size: 14px;
  color: #333;
}

/* 复选框统一样式 */
input[type="checkbox"] {
  width: 17px;
  height: 17px;
  accent-color: #4361ee;
  cursor: pointer;
}

.cart-table .cell-check {
  text-align: center;
}

/* 商品信息 */
.product-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.product-img {
  width: 60px;
  height: 60px;
  border-radius: 8px;
  background: linear-gradient(135deg, #e8ecf1, #d5dbe3);
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 24px;
  flex-shrink: 0;
}

.product-name {
  font-weight: 600;
  color: #1a1a2e;
}

/* 价格 */
.cell-price {
  font-weight: 600;
  color: #1a1a2e;
}

/* 数量控制 */
.quantity-control {
  display: flex;
  align-items: center;
  justify-content: center;
  gap: 0;
}

.qty-btn {
  width: 32px;
  height: 32px;
  border: 1px solid #d0d5dd;
  background: #fff;
  font-size: 16px;
  color: #333;
  cursor: pointer;
  display: flex;
  align-items: center;
  justify-content: center;
  transition: all 0.15s;
  user-select: none;
}

.qty-btn:first-child {
  border-radius: 6px 0 0 6px;
}

.qty-btn:last-child {
  border-radius: 0 6px 6px 0;
}

.qty-btn:hover:not(:disabled) {
  background: #f0f3ff;
  border-color: #4361ee;
  color: #4361ee;
}

.qty-btn:active:not(:disabled) {
  background: #e0e5ff;
}

/* disabled 样式 */
.qty-btn:disabled {
  opacity: 0.35;
  cursor: not-allowed;
  background: #f5f5f5;
  color: #bbb;
}

.qty-input {
  width: 48px;
  height: 32px;
  border: 1px solid #d0d5dd;
  border-left: none;
  border-right: none;
  text-align: center;
  font-size: 14px;
  font-weight: 600;
  color: #333;
  outline: none;
  -moz-appearance: textfield;
}

.qty-input::-webkit-outer-spin-button,
.qty-input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

/* 小计 */
.cell-subtotal {
  font-weight: 700;
  color: #e63946;
  font-size: 15px;
}

/* 删除按钮 */
.btn-delete {
  background: none;
  border: none;
  color: #999;
  font-size: 14px;
  cursor: pointer;
  padding: 6px 10px;
  border-radius: 4px;
  transition: all 0.15s;
}

.btn-delete:hover {
  color: #e63946;
  background: #fff5f5;
}

/* 底部栏 */
.cart-footer {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 16px 28px;
  background: #fafbfc;
  border-top: 1px solid #eee;
}

.footer-left {
  display: flex;
  align-items: center;
  gap: 12px;
}

.select-all-label {
  display: flex;
  align-items: center;
  gap: 6px;
  font-size: 14px;
  color: #555;
  cursor: pointer;
  user-select: none;
}

.select-all-label input[type="checkbox"] {
  margin: 0;
}

.selected-info {
  font-size: 14px;
  color: #888;
  margin-left: 8px;
}

.footer-right {
  display: flex;
  align-items: center;
  gap: 20px;
}

.total-amount {
  display: flex;
  align-items: baseline;
  gap: 4px;
}

.total-label {
  font-size: 14px;
  color: #555;
}

.total-price {
  font-size: 22px;
  font-weight: 700;
  color: #e63946;
}

.btn-checkout {
  padding: 12px 32px;
  background: linear-gradient(135deg, #4361ee, #3a56d4);
  color: #fff;
  border: none;
  border-radius: 8px;
  font-size: 15px;
  font-weight: 600;
  cursor: pointer;
  transition: all 0.2s;
}

.btn-checkout:hover {
  background: linear-gradient(135deg, #3a56d4, #2d44b5);
  box-shadow: 0 4px 12px rgba(67, 97, 238, 0.35);
}

.btn-checkout:active {
  transform: scale(0.98);
}

/* 空购物车 */
.empty-cart {
  text-align: center;
  padding: 60px 20px;
  color: #bbb;
  font-size: 15px;
}

.empty-cart .empty-icon {
  font-size: 48px;
  display: block;
  margin-bottom: 12px;
}
相关推荐
CappuccinoRose4 小时前
前端开发交互体系 - 汇总篇
开发语言·前端·javascript·css·html·交互
zhanlang02171 天前
HTML 零基础入门到企业实战全套教程【第九章】企业开发规范与兼容适配|9.1 主流浏览器兼容问题与解决方案
前端·html
zhanlang02171 天前
HTML 零基础入门到企业实战【第八章 8.6】HTML5 本地存储、拖拽 API、视频音频新特性
html·音视频·html5
inksci2 天前
用飞帆做了个小网页
前端·javascript·css·html
zhanlang02172 天前
HTML 零基础入门到企业实战【第八章 8.5】画布 canvas、SVG 矢量图形基础入门
前端·html
zhanlang02172 天前
HTML 零基础入门到企业实战全套教程【连载 8.4】HTML5 新增表单属性与表单控件
前端·html·html5
狮子座的男孩3 天前
html+css基础:31、响应式布局(媒体类型,媒体特性,运算符,常用阈值)
前端·css·经验分享·html·响应式布局·媒体类型/特性·常用阈值
SemiTris3 天前
Web 前端底层起源:HTML/CSS/JS、浏览器与 HTTP 完整脉络
http·html
狮子座的男孩3 天前
html+css基础:32、BFC(父子元素防止 margin 塌陷,父子元素清除浮动,兄弟元素两栏布局)
前端·css·经验分享·html·bfc·margin塌陷·清除浮动
zhanlang02173 天前
HTML 零基础入门到企业实战全套教程【第八章 8.3】HTML5 语义化标签|SEO 优化、页面布局实战应用
前端·html·html5