我有一个充满图像的页面,我希望每个图像在加载时淡入.我有以下代码,但似乎有问题,基本上有时不是所有的图像淡入.
有没有人有任何建议如何改善这一点.
谢谢
$('.contentwrap img').hide().load(function () {
$(this).fadeIn(1000);
});
Run Code Online (Sandbox Code Playgroud)
有时不是所有的图像都淡入.
是的,这通常是一个相当基本的问题:一些图像在为它们分配加载事件处理程序之前完成加载.高速缓存图像时尤其如此.
如果图像在HTML中,唯一可靠的方法是,包括(非常难看的)内联onload属性:
<img src="..." alt="..." onload="$(this).fadeIn();">
Run Code Online (Sandbox Code Playgroud)
小智 7
如果从浏览器缓存加载图像,则可能不会触发加载事件.为了解释这种可能性,我们可以测试图像的.complete属性的值.
$(document).ready(function() {
$('img').hide();
$('img').each(function(i) {
if (this.complete) {
$(this).fadeIn();
} else {
$(this).load(function() {
$(this).fadeIn();
});
}
});
});
Run Code Online (Sandbox Code Playgroud)
您在 Document.ready 中调用该函数吗?
$(document).ready(function() {
// put all your jQuery goodness in here.
});
Run Code Online (Sandbox Code Playgroud)
http://www.learningjquery.com/2006/09/introducing-document-ready