用html+css写一个选商品系统
时间: 2024-09-17 09:06:17 浏览: 45
创建一个简单的HTML和CSS选商品系统的步骤如下:
**HTML结构:**
```html
<!DOCTYPE html>
<html lang="zh">
<head>
<meta charset="UTF-8">
<title>选商品系统</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<h1>商品列表</h1>
<div class="product-container">
<!-- 商品项将通过JavaScript动态生成 -->
<div class="product-item" id="item-1">
<img src="product1.jpg" alt="产品1">
<p>产品名称1</p>
<input type="checkbox" name="selected-products" value="1">
<span class="price">价格1</span>
</div>
<!-- 更多商品项... -->
</div>
<button id="select-all">全选</button>
<button id="clear-selection">清空选择</button>
<h2>已选商品:</h2>
<ul id="selected-items"></ul>
<script src="script.js"></script>
</body>
</html>
```
**CSS样式 (styles.css):**
```css
.product-container {
display: flex;
justify-content: space-between;
}
.product-item {
margin-bottom: 20px;
}
.product-item img {
width: 150px;
height: auto;
}
.price {
font-weight: bold;
}
```
**JavaScript交互 (script.js):**
```javascript
document.addEventListener('DOMContentLoaded', function() {
// 动态生成商品项并处理勾选事件
const productList = document.querySelectorAll('.product-item');
productList.forEach(function(item) {
item.querySelector('input').addEventListener('change', function() {
if (this.checked) {
let selectedItemsList = document.getElementById('selected-items');
const li = document.createElement('li');
li.textContent = this.value + ' - ' + item.querySelector('.price').textContent;
selectedItemsList.appendChild(li);
} else {
const liToRemove = selectedItemsList.querySelector(`li:contains(${this.value})`);
if (liToRemove) {
liToRemove.remove();
}
}
});
});
document.getElementById('select-all').addEventListener('click', function() {
Array.from(productList).forEach(item => item.querySelector('input').checked = true);
});
document.getElementById('clear-selection').addEventListener('click', function() {
Array.from(productList).forEach(item => item.querySelector('input').checked = false);
document.getElementById('selected-items').innerHTML = '';
});
});
```
阅读全文