首先请不要建议我使用css。
我需要使用Jquery在悬停时在两个图像之间切换。 我需要在页面加载时下载两个图像(两个切换图像)。否则它将首次创建滞后时间。由于我的图像是主页上的两个横幅。我需要做一些创建图像对象的事情,因此预加载它然后切换对象。
我无法使用简单的css执行此操作,因为第一次用户会出现延迟,因为页面加载时图像不存在。它看起来很糟糕。
答案 0 :(得分: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 :(得分: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;
};