[英]Using Radio Buttons to Change Background Image of Div
I am trying to use radio buttons within a form to change the background image of a div but it's simply not working however many methods I try. 我试图在一个表单中使用单选按钮来更改div的背景图像,但它根本无法工作,但我尝试了很多方法。 I'm sure it's something simple within my code but I've just been staring at it for too long. 我确信它在我的代码中很简单,但我只是盯着它看了太久。
I've included my HTML, Javascript and CSS so if anyone could have a look through that'd be swell. 我已经包含了我的HTML,Javascript和CSS,所以如果有人可以看看它会膨胀。
HTML and Javascript: HTML和Javascript:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="styles/styles.css" />
<title>Birthday Card Generator</title>
<script language="javascript">
function bgColor(bg)
{
document.getElementById("ecard").style.backgroundImage = "url(images/" + bg + ".jpg)";
}
</script>
</head>
<body>
<div id="left">
<div id="background">
<form>
<input type="radio" id="bg1" name="bg" value="bg1" onChange="bgColor(this.value)">Background 1
<br /><br />
<input type="radio" id="bg2" name="bg" value="bg2" onChange="bgColor(this.value)">Background 2
</form>
</div>
</form>
</div>
<div id="right">
<div id="ecard">
</div>
</div>
</body>
</html>
CSS CSS
@charset "utf-8";
/* CSS Document */
#left
{
float: left;
width: 50%;
height: 100%;
overflow: scroll;
overflow-x:hidden;
}
#right
{
float: right;
width: 50%;
height: 100%;
overflow: scroll;
}
#background
{
float: left;
width: 100%;
height: 100px;
overflow: scroll;
overflow-y:hidden;
}
#ecard
{
width:400px;
height:300px;
margin:0px auto;
}
I got it to work by changing the name of your function to changeBackground
and cleaning up your HTML a bit: 我通过将你的函数名更改为changeBackground
并清理你的HTML来实现它:
<input type="radio" id="bg1" name="bg" value="bg1" onClick="changeBackground(this.value);" />Background 1
JS: JS:
function changeBackground(bg) {
document.getElementById("ecard").style.backgroundImage = "url(images/" + bg + ".jpg)";
}
The reason for the function name change is that bgColor
is a global property, so calling it as a function resulted in a type error. 函数名称更改的原因是bgColor
是一个全局属性,因此将其作为函数调用会导致类型错误。
Demo: http://jsfiddle.net/verashn/F6zPc/ 演示: http : //jsfiddle.net/verashn/F6zPc/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.