JavaScript实现商品与购物车

需求分析

我希望网页首部为大标题,中间部分摆放商品,尾部购物车结算价格。

目标实现

HTML代码部分不做过多赘述,前面几篇已经说的很多了,都是类似的内容。唯一要注意的是先创建两个容器,分别放产品和购物单。

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple E-commerce Site</title>
<link rel="stylesheet" href="product.css">
</head>
<body>

<header>
  <h1>Simple E-commerce Site</h1>
</header>

<div id="products">
  <!-- Products will be loaded here -->
</div>

<h2>Shopping Cart</h2>
<div id="cart">
  <!-- Cart items will be displayed here -->
</div>

<script src = "product.js"> </script>

</body>
</html>

要实现购物的功能,首先要有商品,这里我们通过const常量的方式来定义,形式如下:

const products = [
  { id: 1, name: 'Product 1', price: 100},
    // ... 略
];

首先需要让用户能够看到商品,定义renderProducts()函数,在页面上渲染产品列表。再遍历产品数组,为每个产品创建一个包含链接、价格、添加按钮的HTML结构,并将每个产品的HTML结构添加到product元素中。当然,这里的链接我们会在之后再讲。

function renderProducts() {
  const productsElement = document.getElementById('products');
  productsElement.innerHTML = '';
  products.forEach(product => {
    const productLink = document.createElement('a');
    productLink.href = product.href;
    productLink.className = 'product-link';
    productLink.innerHTML = `
      <div class="product">
        <h3>${product.name}</h3>
        <p>Price: $${product.price}</p>
        <button class="add-to-cart-btn" onclick="addToCart(${product.id}, event)">Add to Cart</button>
      </div>
    `;
    productsElement.appendChild(productLink);
  });
}

接下去实现点击购物加入购物车的功能:

定义addToCart函数,从产品列表中找到与给定productId匹配的产品,如果不存在则退出函数并打印错误信息(便于调试),一开始的时候从本地存储中获取购物车数据,如果不存在则初始化为空对象。这样就算刷新,购物车也不会清空。具体代码如下(其中部分跳转功能在下期说明):

// Function to add product to cart
function addToCart(productId, event) {
  event.preventDefault(); // 阻止<a>标签的默认行为
  const product = products.find(p => p.id === parseInt(productId));
  if (!product) {
    console.error(`Product with ID ${productId} not found in products array.`);
    return;
  }
  const cart = JSON.parse(localStorage.getItem('cart')) || {};
  cart[productId] = (cart[productId] || 0) + 1;
  localStorage.setItem('cart', JSON.stringify(cart));
  renderCart();
}

然后是购物车相关内容,首先一样要渲染购物车,定义renderCart()函数,对于数量大于0的显示数目并计算价格,如果购物车是空的则显示empty等。这里包含一个删除商品的函数removeFromCart,我们马上来实现它。

// Function to render cart
function renderCart() {
  const cart = JSON.parse(localStorage.getItem('cart')) || {};
  const cartElement = document.getElementById('cart');
  let total = 0;
  cartElement.innerHTML = '';
  Object.keys(cart).forEach(productId => {
    const quantity = cart[productId];
    if (quantity > 0) { // 只显示数量大于0的商品
      const product = products.find(p => p.id === parseInt(productId));
      if (product) {
        const cartItemElement = document.createElement('div');
        cartItemElement.className = 'cart-item';
        cartItemElement.innerHTML = `
          <h3>${product.name} * ${quantity}</h3>
          <p>Price: $${(product.price * quantity).toFixed(2)}</p>
          <button onclick="removeFromCart(${productId})">Remove</button>
        `;
        cartElement.appendChild(cartItemElement);
        total += product.price * quantity;
      }
    }
  });
  if (cartElement.innerHTML === '') {
    cartElement.innerHTML = '<p>Your cart is empty.</p>';
  }
  cartElement.innerHTML += `<h3>Total: $${total.toFixed(2)}</h3>`;
}

remove的逻辑是简单的,数量大于1就减少1,数量到0就在购物车中删除这个商品,代码如下:

// Function to remove product from cart
function removeFromCart(productId) {
  const cart = JSON.parse(localStorage.getItem('cart')) || {};
  if (cart[productId] === undefined) {
    console.error(`Product with ID ${productId} not found in cart.`);
    return;
  }
  cart[productId] = (cart[productId] || 0) - 1;
  if (cart[productId] <= 0) {
    delete cart[productId];
  }
  localStorage.setItem('cart', JSON.stringify(cart));
  renderCart();
}

我们在程序启动的时候渲染产品和购物车:

// Initialize the app
renderProducts();
renderCart();

CSS样式照例贴上来供参考:

/* Reset some default styles */
body,
h1,
h2,
h3,
p,
button,
a {
    margin: 0;
    padding: 0;
    text-decoration: none;
    /* Remove underline from links */
    color: inherit;
    /* inherit text color from parent */
}

/* Set up the body styles */
body {
    font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
    background-color: #f4f4f4;
    color: #333;
    line-height: 1.6;
    overflow-x: hidden;
    /* Prevent horizontal scrollbar */
}

/* Header styles */
header {
    background-color: #007BFF;
    color: #fff;
    padding: 20px 0;
    text-align: center;
    font-size: 24px;
}

/* Products container styles */
#products {
    display: flex;
    flex-wrap: wrap;
    justify-content: space-around;
    padding: 20px;
    max-width: 100%;
    /* Prevent container from causing horizontal scrollbar */
}

/* Product card styles */
.product-link {
    text-decoration: none;
    /* Remove underline from links */
    color: inherit;
    /* inherit text color from parent */
    display: flex;
    flex-basis: calc((100% / var(--products-per-row)) - 20px);
    /* Adjust flex-basis */
    max-width: calc((100% / var(--products-per-row)) - 20px);
    /* Set max-width for responsiveness */
    margin: 10px;
    border-radius: 8px;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
    overflow: hidden;
    /* Hide overflow content */
}

.product {
    background-color: #fff;
    border: 1px solid #ddd;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    width: 100%;
    /* Set width to 100% */
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.product h3 {
    margin-bottom: 10px;
    color: #333;
    font-size: 18px;
}

.product p {
    margin-bottom: 10px;
    color: #666;
}

.product button {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.product button:hover {
    background-color: #218838;
}

/* Customizable number of products per row */
:root {
    --products-per-row: 5;
    /* Default value, can be changed to 2, 4, etc. */
}

/* Cart container styles */
#cart {
    background-color: #fff;
    border: 1px solid #ddd;
    padding: 20px;
    margin: 20px;
    width: 100%;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    max-width: 100%;
    /* Prevent cart from causing horizontal scrollbar */
}

/* Cart item styles */
.cart-item {
    background-color: #f9f9f9;
    border: 1px solid #ddd;
    padding: 10px;
    margin-bottom: 10px;
    border-radius: 5px;
}

.cart-item h3 {
    margin-bottom: 10px;
    color: #333;
    font-size: 16px;
}

.cart-item p {
    margin-bottom: 10px;
    color: #666;
}

.cart-item button {
    background-color: #dc3545;
    color: white;
    border: none;
    padding: 5px 10px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
}

.cart-item button:hover {
    background-color: #c82333;
}

/* Responsive design */
@media (max-width: 768px) {
    :root {
        --products-per-row: 2;
        /* 2 products per row on smaller screens */
    }
}

@media (max-width: 480px) {
    :root {
        --products-per-row: 1;
        /* 1 product per row on very small screens */
    }
}


/* Product link styles */
.product-link {
    display: flex;
    flex-basis: calc((100% / var(--products-per-row)) - 20px);
    max-width: calc((100% / var(--products-per-row)) - 20px);
    margin: 10px;
    text-decoration: none;
    /* Remove underline from links */
    color: inherit;
    /* inherit text color from parent */
    border-radius: 8px;
    overflow: hidden;
    /* Hide overflow content */
}

/* Product card styles */
.product {
    background-color: #fff;
    border: 1px solid #ddd;
    padding: 20px;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
    border-radius: 8px;
    width: 100%;
    transition: transform 0.3s ease, box-shadow 0.3s ease;
}

.product:hover {
    transform: translateY(-5px);
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

/* Button styles */
.add-to-cart-btn {
    background-color: #28a745;
    color: white;
    border: none;
    padding: 10px 20px;
    border-radius: 5px;
    cursor: pointer;
    transition: background-color 0.3s ease;
    margin-top: 10px;
}

.add-to-cart-btn:hover {
    background-color: #218838;
}

特别地,这里为了能够更改商品显示数目,适配各种屏幕,可以自己调整显示数量。

最终的显示效果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值