利用表单、JS、CSS技术,设计实现一个简易的购物车界面
时间: 2023-11-26 15:06:47 浏览: 30
好的,以下是一个简易的购物车界面的示例代码:
HTML代码:
```
<div class="cart">
<div class="cart-items">
<div class="cart-item">
<img src="product1.jpg" alt="Product 1">
<div class="cart-item-info">
<h3>Product 1</h3>
<p>$10.99</p>
<button class="remove-item">Remove</button>
</div>
</div>
<div class="cart-item">
<img src="product2.jpg" alt="Product 2">
<div class="cart-item-info">
<h3>Product 2</h3>
<p>$15.99</p>
<button class="remove-item">Remove</button>
</div>
</div>
</div>
<div class="cart-total">
<p>Total: $26.98</p>
<button class="checkout">Checkout</button>
</div>
</div>
```
CSS代码:
```
.cart {
width: 400px;
border: 1px solid #ccc;
padding: 20px;
}
.cart-items {
margin-bottom: 20px;
}
.cart-item {
display: flex;
margin-bottom: 10px;
}
.cart-item img {
width: 70px;
height: 70px;
object-fit: cover;
margin-right: 10px;
}
.cart-item-info {
display: flex;
flex-direction: column;
}
.cart-item-info h3 {
margin: 0;
margin-bottom: 5px;
}
.cart-item-info p {
margin: 0;
margin-bottom: 10px;
}
.remove-item {
background-color: #ccc;
border: 0;
padding: 5px 10px;
cursor: pointer;
}
.cart-total {
display: flex;
justify-content: space-between;
align-items: center;
}
.checkout {
background-color: #333;
color: #fff;
border: 0;
padding: 10px 20px;
cursor: pointer;
}
```
JavaScript代码:
```
const cartItems = document.querySelector('.cart-items');
const cartTotal = document.querySelector('.cart-total p');
const checkoutBtn = document.querySelector('.checkout');
let total = 0;
function updateTotal() {
cartTotal.textContent = `Total: $${total.toFixed(2)}`;
}
function addItem(name, price) {
const item = `
<div class="cart-item">
<img src="product1.jpg" alt="${name}">
<div class="cart-item-info">
<h3>${name}</h3>
<p>$${price.toFixed(2)}</p>
<button class="remove-item">Remove</button>
</div>
</div>
`;
cartItems.insertAdjacentHTML('beforeend', item);
total += price;
updateTotal();
}
function removeItem(item) {
const price = parseFloat(item.querySelector('p').textContent.slice(1));
total -= price;
updateTotal();
item.remove();
}
cartItems.addEventListener('click', e => {
const removeBtn = e.target.closest('.remove-item');
if (!removeBtn) return;
const item = removeBtn.closest('.cart-item');
removeItem(item);
});
checkoutBtn.addEventListener('click', () => {
alert(`Your total is $${total.toFixed(2)}. Thank you for your purchase!`);
});
```
这个购物车界面使用了HTML的表单元素来显示商品信息和操作按钮,使用了CSS来美化界面,使用了JavaScript来处理添加商品、删除商品和结算的逻辑。购物车界面包括商品图片、商品名称、商品价格、删除商品按钮、总价和结算按钮。用户可以通过点击删除商品按钮来删除对应的商品,并且结算按钮会弹出一个提示框显示总价。