2013-03-21 29 views
0

我有一個帶有2個按鈕的頁面,它們將div中的圖像從一個換成另一個。我想一個圖像是在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

附加說明:如果我將圖像添加到div,如下所示:

圖片顯示,但交換不起作用。 – ckeegan 2013-03-21 18:20:06

回答

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

這將跨瀏覽器很好地工作。

+0

無論誰剛剛評論,而不是刪除他們的評論,你是對的......我把腳本移到HTML下面,它的工作原理!非常感謝。 – ckeegan 2013-03-21 18:30:31

+0

是的,等待DOM加載會導致這種情況。請檢查我的更新答案,以減少突然處理它的方式。 – faino 2013-03-21 18:38:13