复选框通过input标签实现,type设为checkbox,配合label提升可访问性,name属性分组,value提交选中值,checked设置默认选中;JavaScript可通过querySelectorAll获取选中项或监听change事件实时处理;表单提交时仅选中项被发送,后端以数组接收;可通过CSS隐藏原生样式并自定义外观,利用:checked伪类切换状态,实现交互增强。

HTML复选框(checkbox)用于让用户从多个选项中选择一个或多个。它通过 input 标签定义,type 属性设置为 checkbox 来实现。
每个复选框使用 zuojiankuohaophpcninput type="checkbox"> 创建,并建议配合 label 标签提升可访问性。
示例代码:
<input type="checkbox" id="option1" name="fruit" value="apple"> <label for="option1">苹果</label> <input type="checkbox" id="option2" name="fruit" value="banana"> <label for="option2">香蕉</label> <input type="checkbox" id="option3" name="fruit" value="orange" checked> <label for="option3">橙子(默认选中)</label>
表单提交时,只有被选中的复选框才会提交数据。使用 JavaScript 可以动态获取所有选中的项。
立即学习“前端免费学习笔记(深入)”;
常见方法:
// 方法一:通过 querySelectorAll 获取所有选中的 checkbox
const checkboxes = document.querySelectorAll('input[name="fruit"]:checked');
const selectedValues = [];
checkboxes.forEach((box) => {
selectedValues.push(box.value);
});
console.log(selectedValues); // 如:["apple", "orange"]
方法二:绑定事件实时监听选择变化
document.querySelectorAll('input[name="fruit"]').forEach(box => {
box.addEventListener('change', function() {
if (this.checked) {
console.log(this.value + ' 被选中');
} else {
console.log(this.value + ' 被取消');
}
});
});
在 form 中,多个同名复选框可以提交数组式数据。后端通常以数组方式接收(如 PHP 的 $_POST['fruit'][] 或 Node.js 配合解析器)。
<form action="/submit" method="post"> <input type="checkbox" name="hobby" value="reading"> 阅读 <br> <input type="checkbox" name="hobby" value="music"> 听音乐 <br> <input type="checkbox" name="hobby" value="sports"> 运动 <br> <button type="submit">提交</button> </form>
用户提交后,服务器只收到被勾选的 hobby 值。
原生复选框样式受限,可通过隐藏 input 并用 label 模拟来自定义外观。
思路:
示例CSS:
.custom-checkbox {
display: none;
}
.custom-label {
cursor: pointer;
padding: 5px 10px;
border: 1px solid #ccc;
border-radius: 4px;
user-select: none;
}
.custom-checkbox:checked + .custom-label {
background-color: #007bff;
color: white;
}
对应HTML:
<input type="checkbox" class="custom-checkbox" id="cb1"> <label class="custom-label" for="cb1">自定义样式复选框</label>
以上就是HTML复选框怎么定义_HTML复选框checkbox的用法与多选实现的详细内容,更多请关注php中文网其它相关文章!
HTML怎么学习?HTML怎么入门?HTML在哪学?HTML怎么学才快?不用担心,这里为大家提供了HTML速学教程(入门课程),有需要的小伙伴保存下载就能学习啦!
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号