制作一个有线表格,当:1.点击全选复选框时,全选下面四个复选框,再点全选复选框时取消全选; 当下面所有复选框都被选中时,全选复选框选中,否则取消全选框选中2.当鼠标进入表格和离开表格时,改变表格背景色,颜色自定义;3、 点击删除按钮时,判断是否有复选框被选中,如果没有复选框被选中则提示用户进行选择,否则确认删除,并从表格中删除相应行
时间: 2024-03-03 15:51:11 浏览: 123
利用Bootstrap实现表格复选框checkbox全选
好的,这是一个比较复杂的问题,需要用到 HTML、CSS 和 JavaScript 来实现。下面是代码实现:
HTML 代码:
```html
<table id="myTable">
<thead>
<tr>
<th><input type="checkbox" id="checkAll"></th>
<th>Name</th>
<th>Age</th>
<th>Email</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="checkbox" class="check"></td>
<td>John Doe</td>
<td>30</td>
<td>john@example.com</td>
<td><button class="delete">Delete</button></td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>Jane Doe</td>
<td>25</td>
<td>jane@example.com</td>
<td><button class="delete">Delete</button></td>
</tr>
<tr>
<td><input type="checkbox" class="check"></td>
<td>Bob Smith</td>
<td>40</td>
<td>bob@example.com</td>
<td><button class="delete">Delete</button></td>
</tr>
</tbody>
</table>
```
CSS 代码:
```css
table {
border-collapse: collapse;
}
th,
td {
border: 1px solid #ccc;
padding: 8px;
}
#myTable tbody tr:hover {
background-color: #f5f5f5;
}
```
JavaScript 代码:
```js
// 获取元素
const checkAll = document.getElementById("checkAll");
const checks = document.querySelectorAll(".check");
const deleteBtns = document.querySelectorAll(".delete");
const table = document.getElementById("myTable");
// 全选/取消全选
checkAll.addEventListener("click", () => {
checks.forEach((check) => (check.checked = checkAll.checked));
});
// 单个复选框改变时检查是否需要选中/取消全选
checks.forEach((check) => {
check.addEventListener("change", () => {
let allChecked = true;
checks.forEach((check) => {
if (!check.checked) {
allChecked = false;
}
});
checkAll.checked = allChecked;
});
});
// 改变表格背景色
table.addEventListener("mouseenter", () => {
table.style.backgroundColor = "#eee";
});
table.addEventListener("mouseleave", () => {
table.style.backgroundColor = "#fff";
});
// 删除按钮点击事件
deleteBtns.forEach((deleteBtn) => {
deleteBtn.addEventListener("click", () => {
let checkedCount = 0;
checks.forEach((check) => {
if (check.checked) {
checkedCount++;
}
});
if (checkedCount === 0) {
alert("Please select at least one row to delete.");
return;
}
if (confirm("Are you sure you want to delete the selected rows?")) {
checks.forEach((check, index) => {
if (check.checked) {
table.deleteRow(index + 1); // 因为第一行是表头,所以要加 1
}
});
checkAll.checked = false;
}
});
});
```
阅读全文