html+js+css购物车完整代码
时间: 2023-12-27 15:04:06 浏览: 154
以下是一个使用HTML、JS和CSS实现的购物车完整代码示例:
HTML部分:
```html
<!DOCTYPE html>
<html>
<head>
<title>购物车</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<h1>购物车</h1>
<table id="cart">
<thead>
<tr>
<th>商品</th>
<th>数量</th>
<th>单价</th>
<th>小计</th>
<th>操作</th>
</tr>
</thead>
<tbody>
<tr>
<td>商品1</td>
<td><input type="number" value="1"></td>
<td>10.00</td>
<td>10.00</td>
<td><button class="remove">删除</button></td>
</tr>
<tr>
<td>商品2</td>
<td><input type="number" value="1"></td>
<td>20.00</td>
<td>20.00</td>
<td><button class="remove">删除</button></td>
</tr>
</tbody>
<tfoot>
<tr>
<td colspan="3">合计:</td>
<td id="total">30.00</td>
<td></td>
</tr>
</tfoot>
</table>
<script src="script.js"></script>
</body>
</html>
```
CSS部分(style.css):
```css
body {
font-family: Arial, sans-serif;
}
h1 {
text-align: center;
}
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 10px;
text-align: left;
border-bottom: 1px solid #ddd;
}
tfoot td {
font-weight: bold;
}
input[type="number"] {
width: 50px;
}
button.remove {
background-color: #f44336;
color: white;
border: none;
padding: 5px 10px;
cursor: pointer;
}
```
JS部分(script.js):
```javascript
window.onload = function() {
var cartTable = document.getElementById('cart');
var tr = cartTable.getElementsByTagName('tr');
var removeBtns = cartTable.getElementsByClassName('remove');
var total = document.getElementById('total');
// 计算合计
function getTotal() {
var selected = 0;
var price = 0;
for (var i = 0, len = tr.length; i < len; i++) {
if (tr[i].getElementsByTagName('input')[0].checked) {
selected += parseInt(tr[i].getElementsByTagName('input')[1].value);
price += parseFloat(tr[i].cells[3].innerHTML);
}
}
total.innerHTML = price.toFixed(2);
}
// 删除商品
function removeProduct() {
var currentTr = this.parentNode.parentNode;
currentTr.parentNode.removeChild(currentTr);
getTotal();
}
// 绑定删除按钮的点击事件
for (var i = 0, len = removeBtns.length; i < len; i++) {
removeBtns[i].onclick = removeProduct;
}
// 监听数量输入框的变化
for (var i = 0, len = tr.length; i < len; i++) {
tr[i].getElementsByTagName('input')[1].onchange = getTotal;
}
};
```
阅读全文