原生js实现复选框(全选/全不选/反选)效果【含完整代码】
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>复选框全选/全不选/反选示例</title>
<script>
function selectAll(selectAllCheckbox) {
const checkboxes = document.querySelectorAll('.checkbox');
checkboxes.forEach((checkbox) => {
checkbox.checked = selectAllCheckbox.checked;
});
}
function toggleSelect(toggleCheckbox) {
const checkboxes = document.querySelectorAll('.checkbox');
checkboxes.forEach((checkbox) => {
checkbox.checked = !checkbox.checked;
});
}
function isAllSelected() {
const checkboxes = document.querySelectorAll('.checkbox');
return [...checkboxes].every(checkbox => checkbox.checked);
}
function isNoneSelected() {
const checkboxes = document.querySelectorAll('.checkbox');
return [...checkboxes].every(checkbox => !checkbox.checked);
}
</script>
</head>
<body>
<form>
<input type="checkbox" id="selectAll" onclick="selectAll(this)" />全选
<input type="button" value="反选" onclick="toggleSelect()" />
<div>
<input class="checkbox" type="checkbox" />项目1
<input class="checkbox" type="checkbox" />项目2
<input class="checkbox" type="checkbox" />项目3
<input class="checkbox" type="checkbox" />项目4
</div>
</form>
<p>
<input type="button" value="全选" onclick="selectAll(document.getElementById('selectAll'))" />
<input type="button" value="全不选" onclick="selectAll(null)" />
<input type="button" value="检查是否全选" onclick="alert(isAllSelected() ? '全选' : '未全选')" />
<input type="button" value="检查是否全不选" onclick="alert(isNoneSelected() ? '全不选' : '未全不选')" />
</p>
</body>
</html>
这段代码实现了复选框的全选、全不选和反选功能,并提供了检查是否全选和全不选的功能按钮。使用原生JavaScript语法和DOM操作实现,方便理解和学习。
评论已关闭