Css - 带有 js 交互的样式输入复选框



我写是因为我看到这个答案变旧了,不再有效

如何使用 CSS 设置复选框样式?

我想设置复选框框的样式,并稍后在 js 脚本中使用它。

<label>Are you sure?
<input type="checkbox">
</label>

有人可以告诉我如何在2018年做到这一点吗?

您可以使用 :checked 伪类更改复选框的样式。

input[type="checkbox"] {
-webkit-appearance: none;
border: 1px solid #0e0e0e;
width: 20px;
height: 20px;
border-radius: 3px;
}
input[type="checkbox"]:checked {
border: 1px solid red;
position: relative;
}
input[type="checkbox"]:checked:after {
content: "x";
}
<label>Are you sure?
<input type="checkbox">
</label>

我发现这个非常好的教程 W3Schools 你可以通过它,它给出了一个逐步设计复选框的方法。

对于 JavaScript 目标

var checkbox = document.querySelector('input[type="checkbox"]')

checkbox.addEventListener('change',function () {
if(document.querySelector('input[type="checkbox"]:checked')){
//returns true if element is checked 
alert("I am checked");
}
})
<label>Are you sure?
<input type="checkbox">
</label>

这将针对复选框添加更改事件侦听器,该侦听器等待侦听状态从未选中到选中的状态更改,然后使用 if 语句查看值是否已选中。

最新更新