JavaScript-如何更改复选框背景?
我想在不使用jQuery的情况下更改复选框的背景(当然,如果可能的话),因为我不熟悉该库 HTML:JavaScript-如何更改复选框背景?,javascript,html,checkbox,Javascript,Html,Checkbox,我想在不使用jQuery的情况下更改复选框的背景(当然,如果可能的话),因为我不熟悉该库 HTML: 您可以使用内联处理程序中的this传递对复选框的引用,如下所示: html 这样您就可以对元素的数量使用函数了。您正在混合类名和ID。试试这个 HTML: <form name="checkBox"> <input onchange="checkbox()" type="checkbox" id="cbox" /> </form> function
您可以使用内联处理程序中的
this
传递对复选框的引用,如下所示:
html
这样您就可以对元素的数量使用函数了。您正在混合类名和ID。试试这个 HTML:
<form name="checkBox">
<input onchange="checkbox()" type="checkbox" id="cbox" />
</form>
function checkbox(){
var checkbox = document.getElementById('cbox');
if(checkbox.checked === true){
checkbox.style.background = "url('uncheck.png')";
}else{
checkbox.style.background = "url('check.png')";
}
}
一个不需要使用图像的纯CSS解决方案怎么样: HTML:
您指定了一个
class
,并监听id
-将class='cbox'
更改为id='cbox'
它仍然无效-文档。getElementByClass
应该是文档。GetElementsByCassName
我认为您不能为复选框设置背景图像。但是,您可以通过复选框的标签传达复选框的状态。请参阅我的仅使用CSS的解决方案。这里有一个小提琴显示没有设置复选框的背景图像:。我输入了这个,但复选框仍然有默认背景,所有符号都是一样的。可能是其他的吗?@Wiruspwns代码可能是其他的。。?请提供一个演示和图片,它不起作用。是的,我发现,在我张贴了这个问题。我三年与兜售一,一切都是一样的。。默认复选框背景。。
<form name="checkBox">
<input onchange="checkbox(this)" type="checkbox" class="cbox" />
</form>
function checkbox(elm){ // elm now refers to the checkbox
if(elm.checked === true){
elm.style.background = "url('uncheck.png')";
}else{
elm.style.background = "url('check.png')";
}
}
<form name="checkBox">
<input onchange="checkbox()" type="checkbox" id="cbox" />
</form>
function checkbox(){
var checkbox = document.getElementById('cbox');
if(checkbox.checked === true){
checkbox.style.background = "url('uncheck.png')";
}else{
checkbox.style.background = "url('check.png')";
}
}
<form name="checkBox">
<input type="checkbox" id = "checkbox1" />
<label for = "checkbox1"></label>
</form>
form > input[type = "checkbox"] {
display: none;
}
form > label {
display: inline-block;
width: 20px;
height: 20px;
border: 1px solid #000;
border-radius: 3px;
font-size: 20px;
text-align: center;
cursor: pointer;
}
form > input[type = "checkbox"]:checked + label:before {
content:'\2714';
}