2015-05-28 48 views
-1

實際上,在產品頁面中,我們希望減少服務器的負擔,以便在鼠標懸停後的2到3秒後才能顯示圖像。所以,如果用戶懸停光標,我們應該在2秒鐘後打開服務器,並帶來新的圖像。但下面的代碼沒有按照我們的預期工作。如何用延時翻轉圖像?

HTML標籤:

<img class="rollover-images" data-rollover="{bringNewImage()}" src="{bringOldImage()}" /> 

的Javascript:

$('.rollover-images').each(function() { 

     var newSrc = $(this).data('rollover'); 
     if(newSrc == 0) return; 

     var timeout, oldSrc; 
     $(this).hover(function() { 

      timeout = setTimeout(function() { 

       oldSrc = $(this).attr('src'); 
       $(this).attr('src', newSrc).stop(true,true).hide().fadeIn(1); 

      }, 2000); 

     }, function() { 

      clearTimeout(timeout); 
      $(this).attr('src', oldSrc).stop(true,true).hide().fadeIn(1); 

     }); 

    }); 
+0

*發生了什麼? – Alex

+0

問題有問題嗎?爲什麼它是-1? –

回答

1

有幾個問題與發佈代碼

你不能把一個JavaScript函數的HTML屬性並期望它被函數返回值替換。所以你的HTML應該是

<img class="rollover-images" data-rollover="new.png" src="old.png" /> 

你有這個問題,在超時功能。既然你已經開始了一個新的功能範圍,這個值不會是你的img節點。所以你的JS應該是

$(this).hover(function() { 
    var self = this 
    timeout = setTimeout(function() { 
     oldSrc = $(self).attr('src'); 
     $(self).attr('src', newSrc).stop(true, true).hide().fadeIn(1); 
    }, 2000); 
}, function() { 
    clearTimeout(timeout); 
    $(this).attr('src', oldSrc).stop(true, true).hide().fadeIn(1); 
}); 

請注意,我們定義了一個名爲self的新變量,它在setTimeout調用中使用。

+0

非常感謝!它的工作。 HTML樣本僅供參考。我們正在處理代碼作爲我們框架的一部分。 –