我有一个带有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函数中的图像嵌入行不起作用。
答案 0 :(得分:2)
附加事件时删除括号,否则您正在调用该函数而不附加它:
// 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);
哪种方式可以很好地跨浏览器。