将图像添加到 html 类型的输入复选框或单选框

新手上路,请多包涵

我正在尝试为 html 输入类型复选框和收音机指定要用于我的未选中和选中值的图像。

我有这个:

 background: url("image.png") no-repeat;

但它似乎不适用于单选按钮和仅复选框按钮。

有谁知道有用的东西吗?

原文由 f1wade 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 309
2 个回答

我找到并找到了答案。在这些论坛的帮助下 http://forums.digitalpoint.com/showthread.php?t=665980

所有代码都在下面:您可以复制到一个文件并添加您自己的图像,它会起作用。

 <html>
<script type="text/javascript">
//global variables that can be used by ALL the function son this page.
var inputs;
var imgFalse = '52 0 ROff.png';
var imgTrue = '52 0 ROn.png';

//replace the checkbox with an image and setup events to handle it
function replaceChecks() {
    //get all the input fields on the page
    inputs = document.getElementsByTagName('input');

    //cycle trough the input fields
    for(var i=0; i<inputs.length; i++) {

    //check if the input is a checkbox
    if(inputs[i].getAttribute('type') == 'checkbox') {

        //create a new image
        var img = document.createElement('img');

        //check if the checkbox is checked
        if(inputs[i].checked) {
            img.src = imgTrue;
        } else {
            img.src = imgFalse;
        }

        //set image ID and onclick action
        img.id = 'checkImage'+i;
        //set image
        img.onclick = new Function('checkClick('+i+')');

        //place image in front of the checkbox
        inputs[i].parentNode.insertBefore(img, inputs[i]);

        //hide the checkbox
        inputs[i].style.display='none';
    }
}
}

//change the checkbox status and the replacement image
function checkClick(i) {
if(inputs[i].checked) {
    inputs[i].checked = '';
    document.getElementById('checkImage'+i).src=imgFalse;
} else {
    inputs[i].checked = 'checked';
    document.getElementById('checkImage'+i).src=imgTrue;
}
}

</script>
</html>
<body>
<input type="checkbox" />
<script type="text/javascript">replaceChecks();</script>
</body>

原文由 f1wade 发布,翻译遵循 CC BY-SA 2.5 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题