1

我在加载图像后显示图像时遇到问题。我想要的效果是在图像后面显示一个正在加载的 .gif,当它加载时淡入。以下代码适用于我通过 AJAX 加载的任何图像,但是在页面加载时我想要相同的效果。

$(function() {
    $("#products img").hide().bind("load", function() {
        $(this).fadeIn(300);
    });
});

请注意,这在除 IE 之外的所有浏览器中都能正常工作(仅测试 9)。据我了解,它不会触发load事件,因为图像已缓存或图像在事件绑定之前已加载。我希望浏览器缓存图像,因此在图像 src 的末尾添加日期/时间戳并不是一个真正的选择。

有什么办法可以说If the image is already loaded in some form or another, show it. Otherwise hide it and fade it in once it's loaded.吗?

编辑:我尝试设置一个小提琴,但它并不喜欢它。无论如何,如果它有帮助的话

编辑

如果有人感兴趣,我已经对这两个答案进行了快速的 js 性能测试。 (来源:grabilla.com在此处输入图像描述

4

2 回答 2

4

我遇到了同样的问题并像这样解决了它:

 $("#products img").one('load.FadeIn', function () {
     $(this).fadeIn(300);
 });

 $("#products img").trigger('load.FadeIn');

要么图像已经加载并淡入,要么我们手动触发事件。

于 2013-02-27T09:43:39.883 回答
2

您可以添加一个过滤器,它只通过尚未加载的图像:

$("#products img")
  .filter(function(i, img) { return ! img.complete })
  .hide()
  .bind("load", function() {
    $(this).fadeIn(800);
  });

演示

于 2013-02-27T09:49:26.980 回答