2011-06-17 20 views
1

我有這段代碼,我希望只有在加載了backgroundImage後纔會彈出提示。如何使警報在圖像加載後運行?

$('#element').click(function(){ 
    $('#element').css({ 
     backgroundImage: "url('http://www.button.jpg')", 
     backgroundRepeat: 'no-repeat', 
     backgroundPosition: '7px 5px'});; 

alert ("button is loaded"); 

button.jpg是一個小尺寸:3 KB。
但是當我點擊按鈕元素時,首先會彈出ALERT,並在圖像完成編碼後2秒。

我讀到回調
兼談延遲()
兼談超時

但我在編碼新的,並沒有明白怎麼我應該在這裏做。

回答

5

您會首先在圖像上設置一個load事件。

var imgSrc = 'http://www.button.jpg'; 

$('#element').click(function() { 

    var img = new Image, 
     element = $(this); 

    img.onload = function() { 

     element.css({ 
      backgroundImage: "url('" + imgSrc + "')", 
      backgroundRepeat: 'no-repeat', 
      backgroundPosition: '7px 5px' 
     }); 

     alert("button is loaded"); 

    } 

    img.src = imgSrc; 

}); 

jsFiddle

然後,當圖像被加載時,加載回調將被調用並且後臺將被更新。

如果您需要支持IE6並且發現它不會通過再次下載圖像進行合作,您可能需要查看workaround

+0

除了額外的空間,正如我想象的那樣。 :) –

+0

+1良好的解決方法(我認爲):)(甚至更好,如果添加一些解釋...) –

+0

...而事實'imgSrc'被宣佈超出範圍,不知道如果這是必要的。 –

相關問題