2010-08-24 147 views
1

首先請不要建議我使用css來做到這一點。使用jquery懸停切換圖像

我需要使用Jquery在懸停的兩個圖像之間切換。 我需要在頁面加載時下載兩個圖像(兩個切換圖像)。原因其他它會創造一個第一次滯後時間。因爲我的圖像是在主頁上的兩個橫幅。我需要做一些創建圖像對象,從而預先加載它,然後切換對象。

我不能這樣做使用簡單的CSS因爲會有一個滯後的第一次用戶,因爲該圖像不存在頁面加載。它看起來很糟糕。

+0

我發現這個問題尋找其他的東西,但你可以使用CSS來切換這些圖像,並在您的網頁上的圖片標籤,顯示設置爲無。這將完成沒有JavaScript的整個過程。 – 2011-11-23 14:57:19

+0

@AndrewJackman請再次閱讀這個問題,我明確指出:我不能使用簡單的CSS來做這件事因爲第一次爲用戶會有一個滯後,因爲圖像不是在頁面加載時出現。它看起來很糟糕。 – 2011-11-23 17:13:24

+0

是的,我完全理解你的推理,但是有一種方法可以在加載頁面時加載圖像。如果您在身體標籤底部有''。然後,如果稍後通過懸停效果使用'image.jpg',則不會出現延遲,因爲瀏覽器已經下載了圖像。 – 2011-11-24 07:13:14

回答

4
$(function(){ 
    var imgs = [ 
     new Image(), 
     new Image() 
    ]; 

    imgs[0].src = 'http://www.typeofnan.com/pic1.jpg'; 
    imgs[1].src = 'http://www.typeofnan.com/pic2.jpg'; 

    $('#hoverelement').hover(function(){ 
     $(this).html(imgs[0]); 
    }, function(){ 
     $(this).html(imgs[1]); 
    }); 
});​ 

這應該工作,即使我不是當然,如果那是你需要的。您可以將兩個圖像添加onload事件,以確保它們在允許懸停前真正加載。

1

這裏是下面的代碼的快速演示:http://jsbin.com/itunu

HTML:

<!DOCTYPE html> 
<html> 
<head> 
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script> 
<meta charset=utf-8 /> 
<title>Hello world !!</title> 

</head> 
<body> 
    <img /> 
</body> 
</html> 

的Javascript:

var a = []; 

a[0] = "http://i577.photobucket.com/albums/ss219/music_munster/powerpuff-girls-092.jpg"; 
a[1] = "http://img.listal.com/image/459059/500full.jpg"; 


$(document).ready(function() { 
    var source = $.preload(a); 
    $('img').attr('src',source[0].src); //just an acknowledgement (pre-loading done) 
    $('img').hover(function() { 
    $('img').attr('src',source[1].src); 
    },function() { 
    $('img').attr('src',source[0].src);  
    }); 

}); 



//Image Preloading.... 
var cache = []; 
    $.preload = function(arr) { 
    for(var i = 0; i<arr.length; i++) { 
     var img = new Image(); 
     img.src = arr[i]; 
     cache.push(img); 
    } 
    return cache; 
    };