JavaScript -如何改变复选框背景

JavaScript - how to change checkbox background?

本文关键字:改变 复选框 背景 何改变 JavaScript      更新时间:2023-09-26

我想在不使用jQuery的情况下改变复选框的背景(当然如果可能的话),因为我不熟悉那个库。

HTML:

    <form name="checkBox">
        <input onchange="checkbox()" type="checkbox" class="cbox" />
    </form>

JS:

function checkbox(){
    var checkbox = document.getElementByClass('cbox');
    if(document.getElementById('cbox').checked === true){
        checkbox.style.background = "url('uncheck.png')";
    }else{
        checkbox.style.background = "url('check.png')";
    }
}

您混淆了类名和ID。试试这个。

HTML:

<form name="checkBox">
    <input onchange="checkbox()" type="checkbox" id="cbox" />
</form>

JS:

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解决方案:http://jsfiddle.net/7qcE9/1/.

HTML:

<form name="checkBox">
    <input type="checkbox" id = "checkbox1" />
    <label for = "checkbox1"></label>
</form>
CSS:

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';
}

您可以在内联处理程序中使用this传递对复选框的引用,如下所示:

html

<form name="checkBox">
    <input onchange="checkbox(this)" type="checkbox" class="cbox" />
</form>

js

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')";
 }
}

使您可以使用n的元素数函数