jQuery img.load问题 [英] Jquery img.load question

查看:63
本文介绍了jQuery img.load问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用jQuery 循环插件循环浏览某些图像.这些图像全部包含在DIV中.我不希望cycle插件在所有图像都已加载之后,或者至少在前4或5个加载后才运行,以便不会出现尚未加载的图像.有没有简单的方法可以做到这一点?

我尝试将``lastImg''类添加到div中的最后一个img上,并向其中添加一个``load''事件.

Markup
<div id='cycle'>
  <img src=''/>
  <img src=''/>
  <img src='' class='lastImg'/>
</div>

JQuery
    $('lastImg').load(function(){
      $('#cycle').cycle({..});
    });

在Chrome和FF中这似乎还可以,请承认这是个小问题(有时不起作用,也许图像是否在缓存中?),而在IE中则根本不起作用(惊讶,令人惊讶...). /p>

关于如何执行此操作的其他建议?

解决方案

标记:

<div id='cycle'>
  <img src='path1' class='preload' />
  <img src='path2' class='preload' />
  <img src='path3' class='preload'/>
</div>

尝试一下:

var cyclerLoaded = false;
var numberOfPreloaded = 0;

function imageLoaded()
{      
  numberOfPreloaded++;

  if (numberOfPreloaded >= 4 && !cyclerLoaded)
  {
    $('#cycle').cycle({..});
    cyclerLoaded = true;
  }
}

$(document).ready(function()
{      

  $('img.preload').each(function()
  {
    // Get image instance.
    var image = new Image();
    image.src = $(this).attr('src');

    if (image.complete)        
      imageLoaded();        
    else        
      image.onload = imageLoaded;

  });

});

...其中preload类已附加到要预加载的所有图像上.

I am using the jQuery cycle plugin to cycle through some images. These images are all contained inside a DIV. I don't want the cycle plugin to run until after all of the images have loaded, or at least the first 4 or 5 so that an image doesn't appear that isn't loaded yet. Is there an easy way of doing this?

I tried adding a class 'lastImg' to the last img in the div and adding a 'load' event to that e.g.

Markup
<div id='cycle'>
  <img src=''/>
  <img src=''/>
  <img src='' class='lastImg'/>
</div>

JQuery
    $('lastImg').load(function(){
      $('#cycle').cycle({..});
    });

This seems okay in Chrome and FF, admittedly it's a little flakey (sometimes it doesn't work, maybe if the image is in the cache?) and not at all in IE (surprise, surprise...).

Any other suggestions on how I can do this?

解决方案

Markup:

<div id='cycle'>
  <img src='path1' class='preload' />
  <img src='path2' class='preload' />
  <img src='path3' class='preload'/>
</div>

Try this:

var cyclerLoaded = false;
var numberOfPreloaded = 0;

function imageLoaded()
{      
  numberOfPreloaded++;

  if (numberOfPreloaded >= 4 && !cyclerLoaded)
  {
    $('#cycle').cycle({..});
    cyclerLoaded = true;
  }
}

$(document).ready(function()
{      

  $('img.preload').each(function()
  {
    // Get image instance.
    var image = new Image();
    image.src = $(this).attr('src');

    if (image.complete)        
      imageLoaded();        
    else        
      image.onload = imageLoaded;

  });

});

...where the preload class is attached to all images you want to preload.

这篇关于jQuery img.load问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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