2013-11-21 133 views
1

我正尝试使用表单中的单选按钮来更改div的背景图像,但它根本无法正常工作,但我尝试了许多方法。我确信在我的代码中这很简单,但我只是盯着它太久了。使用单选按钮来更改Div的背景图像

我已经包含了我的HTML,Javascript和CSS,所以如果任何人都可以通过看看会膨胀。

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

@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; 
} 
+0

你确定你的IMG SRC工作? –

+0

图片src正在工作,是的。 –

回答

3

我把它改变你的函数的名称changeBackground和清理你的HTML一点的工作:

<input type="radio" id="bg1" name="bg" value="bg1" onClick="changeBackground(this.value);" />Background 1 

JS:

function changeBackground(bg) { 
    document.getElementById("ecard").style.backgroundImage = "url(images/" + bg + ".jpg)"; 
} 

函数名称更改的原因是bgColor是全局属性,因此将其作为函数调用导致类型错误。

演示:http://jsfiddle.net/verashn/F6zPc/

+0

你是一个美妙的代码魔术师。 –