简体   繁体   中英

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. 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 and 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;
}

I got it to work by changing the name of your function to changeBackground and cleaning up your HTML a bit:

<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)";
}

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.

Demo: http://jsfiddle.net/verashn/F6zPc/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM