2011-04-08 17 views
0

基本上我喜歡2張圖片,我想在3秒內顯示一張圖片,然後用另一張圖片替換爲相同的img標籤。如何延遲加載相同區域中的圖像以使其看起來像動畫?

這是我到目前爲止有:

$(function(){ 
    $("#image_area").hide(); 
    $('#W40').click(function(){ 
     $("#image_area img").remove(); 
     show_image_area('40'); 
    });  
}); 

所以流第一隱藏#image_area,然後點擊#W40按鈕時,刪除任何當前圖像中的區域和運行show_image_area功能,功能如下:

function show_image_area(world){ 
    if (!$("#image_area img").length) { //only run if no current image exists 
     $('#image_area').show(); 
     $('#image_area').prepend("<img id='tw_image' src='world+"/7.png' width=\"1000\" height=\"1030\" />"); 
     setTimeout($("#tw_image").attr("src", "world+"/8.png"), 3000); 
    } 
} 

現在,如果我運行這些代碼時,8.png幾乎立即顯示,有,我想沒有任何的3秒延遲。

回答

1

你必須在代碼中額外「:應該是$("#tw_image").attr("src", world+"/8.png")

而且,我會把$("#tw_image").attr("src", world+"/8.png")在它自己的功能

function SwapImage(world) 
{ 
    $("#tw_image").attr("src", world+"/8.png"); 
} 

那麼你的最後一行更改爲setTimeout(SwapImage(world), 3000);

+0

謝謝你們,每一個回答是好,看起來這個是最快的,所以我選擇了這個。謝謝 – KoKo 2011-04-08 20:30:31

0

這是因爲setTimeout的第一個參數不是一個函數 此外還有一個額外的報價 此外,「世界」變量可能需要閉包(c不記得)。 嘗試

function show_image_area(world){ 
    if (!$("#image_area img").length) { //only run if no current image exists 
     $('#image_area').show(); 
     $('#image_area').prepend("<img id='tw_image' src='world+"/7.png' width=\"1000\" height=\"1030\" />"); 
     var myWorld = world; 
     setTimeout(function() {$("#tw_image").attr("src", myWorld+"/8.png");}, 3000); 
    } 
} 
0

setTimeout調用是有點過:

setTimeout($("#tw_image").attr("src", "world+"/8.png"), 3000); 

的第一個參數應該是要執行的函數:

setTimeout(function() { $("#tw_image").attr("src", "world/8.png") }, 3000); 

而且,我不知道什麼是「世界「,所以我把它合併到新的src路徑來修復一個流浪的雙引號。

1

這個心不是完全測試,但給你一個想法:

$(function(){ 
    $("#image_area").hide(); 
    $('#W40').click(function(){ 
     $("#image_area img").remove() 
     show_image_area('40'); 
    }); 
}); 

function show_image_area(world){  
    var newImg = $('<img />').css({width: 1000, height: 1030}).attr({id: 'tw_image', src: world+'/7.png'); 
    if (!$("#image_area img").length) { //only run if no current image exists 
     $('#image_area').prepend(newImg).show('fast'); 
     setTimeout(function() { 
      $("#tw_image").attr("src", world+"/8.png"); 
     }, 3000); 
    } 
} 

基本上你立刻射擊的setTimeout函數,而不是在一個函數傳遞稍後發射