简体   繁体   English

预加载图片,(来源于javascript)

[英]Preloading Image, (source in javascript)

Ok I previously asked how to do a javascript image hover effect, however the effect doesn't allow the images to be previously preloaded. 好我之前曾问过如何进行javascript图像悬停效果,但效果不允许先前预装图像。 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 . 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. 这将在运行JavaScript时加载它们。 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. 它们的load事件没有处理程序,因此您可能希望添加一个并且不显示悬停效果,直到它们实际上已被下载。

Create div and put your rollover/hover images in it then hide the div 创建div并将翻转/悬停图像放入其中然后隐藏div

<div style="display:none">
    <img src="" />
    <img src="" />
    etc..
</div

This will load the images without having to use javascript at all, but there is a known problem with Opera using this method.. But I use it all the time works fine. 这将加载图像而不必使用javascript,但Opera使用这种方法存在一个已知的问题..但我一直使用它工作正常。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM