如何使用 css 和 javascript 更改标签的背景图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14226511/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can one change the background image of a label using css with javascript
提问by Nick
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 将图像从当前图像更改为单击第二张图片并选择复选框时,根据我对 javascript 的了解,它可以工作,有什么想法吗?由于之前 ie 7 和 8 的问题,它也必须是这样
html:
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:
css:
label {
border:1px solid red;
display:inline-block;
}
#label-interest1 {
background-image: url(images/internetbutton.gif);
width: 152px;
height:152px;
}
javascript:
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/ubran/11/edit
回答by bfavaretto
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)';
}
}