加载图片后显示图片时出现问题。我想要的效果是在图像后面显示一个加载的.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.
吗?编辑:我尝试设置一个小提琴,但它不是很喜欢。 Here it is anyway if it's helpful
编辑
如果有人对这两个答案感兴趣,请I've put up a quick js performance test。
(来源:grabilla.com)
最佳答案
您可以添加一个过滤器,该过滤器仅传递尚未加载的图像:
$("#products img")
.filter(function(i, img) { return ! img.complete })
.hide()
.bind("load", function() {
$(this).fadeIn(800);
});
demo