HTML+css+JavaScript实现购物车功能代码
时间: 2023-10-02 18:12:01 浏览: 137
HTML:
```html
<!DOCTYPE html>
<html>
<head>
<title>购物车</title>
<meta charset="UTF-8">
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>购物车</h1>
<table>
<thead>
<tr>
<th>商品名称</th>
<th>单价</th>
<th>数量</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<tbody id="cart-list">
<tr>
<td>商品1</td>
<td>100</td>
<td><input type="number" min="1" value="1" onchange="changeQuantity(this)"></td>
<td>100</td>
<td><button onclick="removeItem(this)">删除</button></td>
</tr>
<tr>
<td>商品2</td>
<td>200</td>
<td><input type="number" min="1" value="1" onchange="changeQuantity(this)"></td>
<td>200</td>
<td><button onclick="removeItem(this)">删除</button></td>
</tr>
<tr>
<td>商品3</td>
<td>300</td>
<td><input type="number" min="1" value="1" onchange="changeQuantity(this)"></td>
<td>300</td>
<td><button onclick="removeItem(this)">删除</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<th colspan="3">合计:</th>
<th id="total-price">600</th>
<th><button onclick="clearCart()">清空购物车</button></th>
</tr>
</tfoot>
</table>
</body>
<script src="script.js"></script>
</html>
```
CSS:
```css
table {
border-collapse: collapse;
margin: 20px auto;
}
th, td {
border: 1px solid #ccc;
padding: 10px;
text-align: center;
}
th {
background-color: #eee;
}
button {
background-color: #f00;
color: #fff;
border: none;
padding: 5px 10px;
cursor: pointer;
}
input[type="number"] {
width: 50px;
text-align: center;
}
```
JavaScript:
```javascript
// 获取购物车商品列表
let cartList = document.getElementById('cart-list').rows;
// 计算总价
function calcTotalPrice() {
let totalPrice = 0;
for (let i = 1; i < cartList.length - 1; i++) {
let quantity = cartList[i].cells[2].children[0].value;
let price = cartList[i].cells[1].innerHTML;
let subtotal = quantity * price;
cartList[i].cells[3].innerHTML = subtotal;
totalPrice += subtotal;
}
document.getElementById('total-price').innerHTML = totalPrice;
}
// 改变商品数量
function changeQuantity(input) {
if (input.value < 1) {
input.value = 1;
}
calcTotalPrice();
}
// 删除商品
function removeItem(button) {
let row = button.parentNode.parentNode;
row.parentNode.removeChild(row);
calcTotalPrice();
}
// 清空购物车
function clearCart() {
for (let i = 1; i < cartList.length - 1; i++) {
cartList[i].parentNode.removeChild(cartList[i]);
}
document.getElementById('total-price').innerHTML = 0;
}
```
这段代码实现了一个简单的购物车功能,可以添加商品、删除商品、修改数量,并且会实时计算总价。
阅读全文