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

标签 html input checkbox radio-button

我正在尝试指定一个图像,用于 html 输入类型复选框和单选框的未选中和选中值。

我有这个:

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

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

有人知道有用的东西吗?

最佳答案

我已经找到并解决了这个问题。 在这些论坛的帮助下 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>

关于html - 将图像添加到 html 类型的输入复选框或单选框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5117116/

相关文章:

html - colspan ='*'怎么了?

css - 使 HTML5 视频海报与视频本身大小相同

jQuery 更改占位符文本颜色

jquery - 构建jquery复选框 - 无法设置选中值

javascript - 选中的复选框背景不起作用

javascript - 什么是 XHTML 角色属性?你用它来做什么?

javascript - Selenium Web 驱动程序 - 找不到表单字段

c - C中的输入切换

html - 禁止在 html5 中的数字字段中输入字母

php - 根据表单输入更改 SQL "Where"子句