要在原生HTML、JS和CSS中添加购物车效果,你可以创建一个简单的购物车界面,并且使用JavaScript来处理添加商品到购物车的逻辑。以下是一个简单的例子:
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Shopping Cart Example</title>
<style>
.cart { border: 1px solid #eee; width: 300px; margin: 20px; padding: 10px; }
.cart-item { margin-bottom: 10px; padding-bottom: 10px; border-bottom: 1px solid #eee; }
.cart-item-remove { cursor: pointer; }
</style>
</head>
<body>
<h1>Product List</h1>
<div class="product" data-price="99" data-name="Product 1">
<button class="add-to-cart">Add to Cart</button>
Product 1 - $99
</div>
<div class="product" data-price="199" data-name="Product 2">
<button class="add-to-cart">Add to Cart</button>
Product 2 - $199
</div>
<div class="cart">
<h2>Shopping Cart</h2>
<div class="cart-items"></div>
</div>
<script>
let cartItems = document.querySelector('.cart-items');
// Event listener for adding to cart
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('.add-to-cart').forEach(button => {
button.addEventListener('click', event => {
let product = event.target.parentNode;
addToCart(product);
});
});
});
// Function to add product to cart
function addToCart(product) {
let price = product.dataset.price;
let name = product.dataset.name;
// Create cart item element
let cartItem = document.createElement('div');
cartItem.classList.add('cart-item');
cartItem.innerHTML = `<span>${name} - $${price}</span> <button class="cart-item-remove" data-name="${name}">Remove</button>`;
// Event listener for removing from cart
cartItem.querySelector('.cart-item-remove').addEventListener('click', function() {
removeFromCart(this.dataset.name);
});
// Add cart item to cart
cartItems.appendChild(cartItem);
}
// Function to remove product from cart
function removeFromCart(name) {
cartItems.querySelectorAll('.cart-item').forEach(item => {
if(item.textContent.includes(name)) {
cartItems.removeChild(item);
}
});
}
</script>
</body>
</html>
这个例子中,我们有一个产品列表,每个产品都有一个"Add to Cart"按钮。当按钮被点击时,产品信息会被添加到购物车中,显示在页面底部的<div class="cart-items"></div>
区域。每个购物车中的条目都有一个"Remove"按钮,点击后会将该产品从购物车中移除。这个例子使用了HTML5的data-*
属性来存储产品的价格和名称,这些数据可以