【问题标题】:Using Radio Buttons to Change Background Image of Div使用单选按钮更改 Div 的背景图像
【发布时间】:2013-11-21 00:32:34
【问题描述】:

我正在尝试使用表单中的单选按钮来更改 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;
}

【问题讨论】:

  • 你确定你的 img src 工作正常吗?
  • Image src 工作正常,是的。

标签: javascript html css forms background-image


【解决方案1】:

我通过将你的函数名称更改为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/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 1970-01-01
    • 2011-12-14
    • 2013-09-07
    相关资源
    最近更新 更多