如何使用带有javascript的css更改标签的背景图像

时间:2021-09-20 00:23:57

This one is a real headache, I have three check boxes in a form that i have labels for, and the labels have background images set with cess, the question is, how exactly do i get my javascript to change the image from curent image to a second image when it is clicked and selects the checkbox, from what i know of javascript, it shold work, any ideas? Also it does have to be this way due to previous issues with ie 7 and 8

这个是一个真正令人头痛的问题,我有一个表格中有三个复选框,我有标签,标签上有用cess设置的背景图片,问题是,我是如何得到我的javascript来将图像从curent图像更改为单击它时的第二个图像并选择复选框,从我所知道的javascript,它的工作,任何想法?由于先前的问题,即7和8,它也必须是这种方式

html:

    <input type="checkbox" name="interest1" id="interest1" value="interested"style="display:block">
    <input type="checkbox" name="interest2" id="interest2" value="interested"style="display:block">
    <input type="checkbox" name="interest3" id="interest3" value="interested"style="display:block">
    <p align="center">
    <label for="interest_inet" id="label-interest1" onClick="func()"></label>

css:

label {
  border:1px solid red;
  display:inline-block;
}

#label-interest1 {
  background-image: url(images/internetbutton.gif);
  width: 152px;
  height:152px;
}

javascript:

<script type="text/javascript">
function func()
{

if(document.getElementById('interest_inet').checked)
{
    document.getElementById('label-interest1').style.backgroundImage=url(images/internetbutton.gif);
}
else
{
    document.getElementById('label-interest1').style.backgroundImage=url(internetbuttonchecked.gif);
}
}
</script>

here is a live code exampleish: http://jsbin.com/uburan/11/edit

这是一个实时代码示例:http://jsbin.com/uburan/11/edit

1 个解决方案

#1


8  

You seem to just be missing some quotes (the value of style.backgroundImage should be a string):

你似乎只是缺少一些引号(style.backgroundImage的值应该是一个字符串):

function func()
{
    var label = document.getElementById('label-interest1');
    if(document.getElementById('interest_inet').checked)
    {
        label.style.backgroundImage = 'url(images/internetbutton.gif)';
    }
    else
    {
        label.style.backgroundImage = 'url(internetbuttonchecked.gif)';
    }
}

#1


8  

You seem to just be missing some quotes (the value of style.backgroundImage should be a string):

你似乎只是缺少一些引号(style.backgroundImage的值应该是一个字符串):

function func()
{
    var label = document.getElementById('label-interest1');
    if(document.getElementById('interest_inet').checked)
    {
        label.style.backgroundImage = 'url(images/internetbutton.gif)';
    }
    else
    {
        label.style.backgroundImage = 'url(internetbuttonchecked.gif)';
    }
}