繁体   English   中英

在页面加载上设置div的背景

[英]setting background of div on page load

我有一个带有2个按钮的页面,可以将div中的图像从一个交换到另一个。 我想在页面加载时将图像放在div中,这是我的尝试:

脚本:

<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>

使用上面的代码,交换执行完全符合预期,如果在startPic函数中设置了警报,则它在图像嵌入行之前有效,但如果警报在图像嵌入行下方则不起作用。 由于某种原因,startPic函数中的图像嵌入行不起作用。

附加事件时删除括号,否则您正在调用该函数而不是附加它:

// 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();

你总是可以用事件监听器做事; 就像是:

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

这将很好地跨浏览器。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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