js实现复选框
实现复选框的基本方法
使用HTML的<input type="checkbox">元素创建复选框,并通过JavaScript监听其变化。
<input type="checkbox" id="myCheckbox">
<label for="myCheckbox">选择此项</label>
const checkbox = document.getElementById('myCheckbox');
checkbox.addEventListener('change', function() {
if (this.checked) {
console.log('复选框被选中');
} else {
console.log('复选框未被选中');
}
});
获取复选框状态
可以通过checked属性获取或设置复选框的选中状态。
// 获取状态
const isChecked = checkbox.checked;
// 设置状态
checkbox.checked = true; // 选中
checkbox.checked = false; // 取消选中
处理多个复选框
当需要处理一组复选框时,可以为它们添加相同的name属性或class。
<input type="checkbox" name="fruit" value="apple"> 苹果
<input type="checkbox" name="fruit" value="banana"> 香蕉
<input type="checkbox" name="fruit" value="orange"> 橙子
const fruits = document.getElementsByName('fruit');
fruits.forEach(checkbox => {
checkbox.addEventListener('change', function() {
const selectedFruits = Array.from(fruits)
.filter(c => c.checked)
.map(c => c.value);
console.log('选中的水果:', selectedFruits);
});
});
全选/全不选功能
实现一个控制多个复选框的全选功能。
<input type="checkbox" id="selectAll"> 全选/全不选
<div id="checkboxGroup">
<input type="checkbox" class="item"> 选项1
<input type="checkbox" class="item"> 选项2
<input type="checkbox" class="item"> 选项3
</div>
const selectAll = document.getElementById('selectAll');
const items = document.querySelectorAll('.item');
selectAll.addEventListener('change', function() {
items.forEach(checkbox => {
checkbox.checked = this.checked;
});
});
使用事件委托优化性能
对于大量复选框,使用事件委托可以提高性能。
document.getElementById('checkboxGroup').addEventListener('change', function(e) {
if (e.target.classList.contains('item')) {
console.log('复选框状态改变:', e.target.checked);
}
});
自定义复选框样式
通过隐藏原生复选框并使用CSS自定义样式。
<label class="custom-checkbox">
<input type="checkbox">
<span class="checkmark"></span>
自定义复选框
</label>
.custom-checkbox {
position: relative;
padding-left: 25px;
cursor: pointer;
}
.custom-checkbox input {
position: absolute;
opacity: 0;
}
.checkmark {
position: absolute;
top: 0;
left: 0;
height: 18px;
width: 18px;
background-color: #eee;
border-radius: 3px;
}
.custom-checkbox input:checked ~ .checkmark {
background-color: #2196F3;
}
.checkmark:after {
content: "";
position: absolute;
display: none;
}
.custom-checkbox input:checked ~ .checkmark:after {
display: block;
}
.custom-checkbox .checkmark:after {
left: 6px;
top: 2px;
width: 5px;
height: 10px;
border: solid white;
border-width: 0 3px 3px 0;
transform: rotate(45deg);
}
使用第三方库
对于复杂需求,可以考虑使用第三方库如jQuery或专门的UI库。
// 使用jQuery
$('#myCheckbox').change(function() {
if ($(this).is(':checked')) {
console.log('复选框被选中');
}
});






