2011-03-19 84 views
2

我將一個遠程文件加載爲背景圖像,根據互聯網連接,這可能需要長達2秒的時間。當背景圖像加載完成時調用一個函數

我想在背景圖像完成加載時觸發一個函數。

它的工作是這樣的(儘管這顯然並非如此)

$("body").css("background image","url('very_big_remote_image')", 
     function(data){alert("done")} 
     ); 

回答

3

嘗試此,基本上我加載圖像對象並設置其源到背景。一旦它加載我改變的背景和火回調:

var img = new Image(); 
img.onload = function() { 
    $("body").addClass("bg"); 
    //the callback function call here 
}; 
img.src = 'very_big_remote_image'; 

此圖片永遠不會顯示,只是力量的瀏覽器加載它,然後它被緩存。

然後讓這個在你的CSS:

body.bg { 
    /* change the position or repeat or whatever else you need in this line */ 
    background: url('/path/to/the/image/above.jpg') no-repeat 0 0 transparent; 
} 
+0

聰明!將嘗試它現在 – 2011-03-19 23:51:41

+0

它的奇怪 - 圖像需要一段時間加載,然後背景圖像不會改變,回調觸發 – 2011-03-20 00:09:53

+0

這樣做,而不是.css行:$(「body」)。addClass(「bg 「);然後有一個css body.bg {background:url(「該路徑的圖像」)} – moe 2011-03-20 01:26:02

1

jQuery有一個回調機制的負載事件功能:

$("<img />").attr('src', 'img/pic.png').load(function() { /* Do stuff */ }); 

有許多的變化。

http://jquery-howto.blogspot.com/2009/02/preload-images-with-jquery.html

http://api.jquery.com/load-event/

+0

我不相信會TACH背景圖像。 – William 2011-03-19 23:12:12

+0

是的,它不會http://jsfiddle.net/38zqy/ – William 2011-03-19 23:16:07

+0

它會工作 - 我打算/ *做的東西* /評論是你實際設置背景圖像的地方。 moe的解決方案充分發揮它的作用。 – jbrookover 2011-03-20 15:04:49

相關問題