预加载图像,(源代码在JavaScript中) [英] Preloading Image, (source in javascript)

查看:82
本文介绍了预加载图像,(源代码在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];
        }
}();

jsFiddle.

...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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆