预加载图像,(源代码在JavaScript中) [英] Preloading Image, (source in javascript)
问题描述
好的,我以前问过如何做一个JavaScript图像悬停效果,但是效果不允许图像预先加载。我想知道是否有人可以帮助我改进/制作新的脚本,可以预先载入请求的图像。这里是代码:
$('#nav li a img')。each(function(){
var originalSrc = this.src,
hoverSrc = originalSrc.replace(/ \。(gif | png | jpe?g)$ /''_hover。$ 1');
$( this).hover(function(){
this.src = hoverSrc;
},function(){
this.src = originalSrc;
});
});
您可以使用通用的...
p>
(function(){
var imgs = ['a.jpg','b.jpg'],
imgsLength = imgs.legnth,
index = 0,
loadNextImage = function(){
var image = new Image();
image.onload = function(){
if(index == imgsLength){
return;
}
index ++;
loadNextImage();
}
$ b $ image.src = imgs [index];
}
}();
jsFiddle 。
...或者您的具体示例...
$('#nav li a img')。 each(function(){
var originalSrc = this.src,
hoverSrc = originalSrc.replace(/ \。(gif | png | jpe?g)$ /'' _hover。$ 1');
image = new Image();
image.src = hoverSrc;
$ b $(this).hover(function(){
this.src = hoverSrc;
},function(){
this.src = originalSrc;
});
});
这会在JavaScript运行时加载它们。在它们的 load
事件中没有处理程序,因此您可能希望添加一个,并且在实际上已下载之前不显示悬停效果。
Ok I previously asked how to do a javascript image hover effect, however the effect doesn't allow the images to be previously preloaded. I was wondering if anyone could help me improve/make new script that will preload the images requested. Here is the code:
$('#nav li a img').each(function() {
var originalSrc = this.src,
hoverSrc = originalSrc.replace(/\.(gif|png|jpe?g)$/, '_hover.$1');
$(this).hover(function() {
this.src = hoverSrc;
}, function() {
this.src = originalSrc;
});
});
You could use a generic one...
(function() {
var imgs = ['a.jpg', 'b.jpg'],
imgsLength = imgs.legnth,
index = 0,
loadNextImage = function() {
var image = new Image();
image.onload = function() {
if (index == imgsLength) {
return;
}
index++;
loadNextImage();
}
image.src = imgs[index];
}
}();
...or for your specific example...
$('#nav li a img').each(function() {
var originalSrc = this.src,
hoverSrc = originalSrc.replace(/\.(gif|png|jpe?g)$/, '_hover.$1');
image = new Image();
image.src = hoverSrc;
$(this).hover(function() {
this.src = hoverSrc;
}, function() {
this.src = originalSrc;
});
});
This will load them all when the JavaScript is ran. There is no handler on their load
event, so you may wish to add one and not display the hover effect until they have in fact been downloaded.
这篇关于预加载图像,(源代码在JavaScript中)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!