我有一个充满图像的页面,我希望它们中的每一个在加载时都会淡入。我有以下代码可以工作但似乎有问题,基本上有时并非所有图像都会淡入。
有没有人对如何改进这一点有任何建议。
谢谢
$('.contentwrap img').hide().load(function () {
$(this).fadeIn(1000);
});
有时并非所有图像都会淡入。
是的,这通常是一个相当基本的问题:某些图像在您为它们分配加载事件处理程序之前完成加载。当图像被缓存时,这种情况尤其可能发生。
如果图像在 HTML 中,不幸的是,唯一可靠的方法是包含一个(非常丑陋的)内联 onload 属性:
<img src="..." alt="..." onload="$(this).fadeIn();">
如果图像是从浏览器缓存中加载的,则可能不会触发 load 事件。为了解释这种可能性,我们可以测试图像的 .complete 属性的值。
$(document).ready(function() {
$('img').hide();
$('img').each(function(i) {
if (this.complete) {
$(this).fadeIn();
} else {
$(this).load(function() {
$(this).fadeIn();
});
}
});
});
将这段代码放在网站的部分中:
<script>
$('body').ready(function() {
$('img').hide();
$('img').each(function(i) {
if (this.complete) {
$(this).fadeIn();
} else {
$(this).load(function() {
$(this).fadeIn(2000);
});
}
});
});
</script>
这可能不是最有说服力的解决方案,但它可以完成工作。如果您想查看它的实际示例,请查看我使用它的这个网站。
您可以首先使用一些 CSS 确保您的图像默认隐藏(消除对 jQueryhide
调用的需要),
.contentwrap img {
display:none;
}
然后,在您的 document.ready 中,您可以尝试以下操作。我承认这里会有一些冗余,因为某些图像可能(在幕后)试图淡入两次,但最终结果看起来是一样的。这是我在试图给出一个简单的答案时承认的权衡。
情况将是在您的 document.ready 中,一些图像可能已经加载(尤其是那些已经缓存的图像),而另一些可能尚未完成。
// fade in images already loaded:
$('.contentwrap img').fadeIn(1000);
// and tell pending images to do the same, once they've finished loading:
$('.contentwrap img').load(function () {
$(this).fadeIn(1000);
});
由于 jQuery 将“堆叠”您的动画效果,一旦某些东西完全淡入,您可以再次对其调用 fadeIn,并且不会(明显地)发生任何事情。
如果这是不可接受的,您可能会设计一些更复杂的方法来检查哪些图像已经淡入,哪些没有,然后再设置加载事件。
祝你好运!
我刚刚在这个线程上回答了这个问题:jQuery How do you get an image to fade in on load?
为我工作!
put your code inside of this function. If you use $(document) it works as soon as the dom is loaded. If you use body it starts once the body is fully loaded. That way your images will always fade in after the body is loaded.
$('body').ready(function() {
//your code here
});
我使用 David DeSandro 的酷脚本来检查图像是否已加载。(例如,您可以编写一个向加载的图像添加类的函数,因此它们将使用 css 过渡淡入。检查一下:
http ://desandro.github.io/imagesloaded/
为了处理缓存的图像,bobince 的解决方案有效,但正如他所说,它非常难看。
另一种解决方案是在 css 中隐藏您的图像并使用以下 javascript:
$(window).load(function(){
$('.contentwrap img').not(':visible').fadeIn(1000);
});
function showImages() {
$('.contentwrap img').load(function () {
$(this).fadeIn(1000);
});
});
showImages();
这样,大多数图像都可以正确加载,如果它们被缓存并立即隐藏(加载函数没有时间被触发),页面的加载事件将使它们出现。页面的加载事件确保所有内容都已加载。
我最近处理了这个烂摊子。我回答了这个类似的问题,但这并不完全是你要问的......
你在 Document.ready 中调用那个函数吗?
$(document).ready(function() {
// put all your jQuery goodness in here.
});
http://www.learningjquery.com/2006/09/introducing-document-ready
你可以把所有的图像放到一个图像中然后淡入,但是它们会同时出现,这将是一个大文件。这取决于你想用它做什么。