简体   繁体   中英

setting background of div on page load

I have a page with 2 buttons that swap an image in a div from one to the other. I would like a image to be in the div when the page loads, this is my attempt:

Script:

<script type="text/javascript">
function startPic(){
    document.getElementById('imageRoll').style.backgroundImage="url(balanceSheet.jpg)";
}
function changeStyle1(){
    document.getElementById("imageRoll").style.backgroundImage="url(balanceSheet.jpg)";
}
function changeStyle2(){
    document.getElementById("imageRoll").style.backgroundImage="url(incomeStatement.jpg)";
}
document.body.onload = startPic();
</script>

HTML:

<div style="width:auto; float: left;">
<div style="width:200px; height:30px; padding: 5px;"><a href="#" onmouseover="changeStyle1()"><img style="border: 0px; vertical-align:middle; padding: 5px;" onmouseover="this.src='standardButton_over.png'" onmouseout="this.src='standardButton.png'" src="standardButton.png" /></a>See balance sheet</div>
<div style="width:200px; height:30px; padding: 5px;"><a href="#" onmouseover="changeStyle2()"><img style="border: 0px; vertical-align:middle; padding: 5px;" onmouseover="this.src='standardButton_over.png'" onmouseout="this.src='standardButton.png'" src="standardButton.png" /></a>See income statement</div>
</div>
<div id="imageRoll" style="background-repeat:no-repeat; width:335px; height:465px; float: left;"></div>

Using the above code the swap performs exactly as expected, and if an alert is set in the startPic function it works if it is before the image embed line, but the alert does not work if it is below the image embed line. For some reason the image embed line in the startPic function does not work.

Remove the parenthesis when you attach the event, else you are calling the function and not attaching it:

// good - attaches the function to the onload of the body
document.body.onload = startPic;
// bad - won't work as you would expect
document.body.onload = startPic();

You could always do things with event listeners; something like:

var load = function(fn){
    var d = document;
    if(d.addEventListener) {
        d.addEventListener("DOMContentLoaded", fn, false);
    } else {
        d.attachEvent("onreadystatechange", function(){
            if(d.readyState === "complete") {
                fn();
            }
        });
    }
};
load(startPic);

Which will works cross browser quite nicely.

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