假设我的 html 文档中有几个 img 标签,所有这些标签都应该显示在一次显示一张图像的幻灯片中。
<div id="gallery">
<img class="slide" src="images/1.png" width="600" height="400" alt=""/>
<img class="slide" src="images/2.png" width="600" height="400" alt=""/>
<img class="slide" src="images/3.png" width="600" height="400" alt=""/>
<img class="slide" src="images/4.png" width="600" height="400" alt=""/>
</div>
我不想显示这些图像,直到它们全部加载完毕,一旦它们全部加载完毕,我想将它们显示为幻灯片(这部分并不重要)。
我无法真正理解它是如何工作的是在隐藏时加载图像。假设我在 $.ready 之后用 display:none
隐藏了它们,这不会阻止它们在某些浏览器中加载吗?如果我让它们可见,一些图像可能会在所有图像加载之前出现,这是不可取的。我不想使用 ajax 加载它们。
再次说明我正在尝试做的事情:
将图片保存在 html 中,而不是使用 ajax 加载它们
在所有加载完成之前不显示它们
一些建议如何实现这一点?我对如何在加载所有内容时显示它们不感兴趣,我感兴趣的是如何在加载时隐藏它们并且它们仍然会加载。谢谢!
最佳答案
首先,您需要确保最初没有显示任何图像。为此,您需要更改样式表。
请注意,仅仅因为 css 设置为 display: none
,not 是否意味着浏览器不加载它。浏览器仍然加载图像,只是不显示它。
在这种情况下,您在样式表中的做法:
/* prevent images from being displayed before they are loaded ready */
#gallery img {
display: none;
}
然后,使用一些 jQuery,在图像完全加载时显示它们:
jQuery(function($) {
$('#gallery img').load(
function() {
$(this).show();
}
);
});
这将在加载时显示每个图像。
或
如果您想等到所有 都加载完毕,您的 jQuery 会有点不同:
jQuery(function($) {
// Get count of images
var icount = $('#gallery img').length;
// Initialize count to track loaded images
var lcount = 0;
$('#gallery img').load(
function() {
// If the loaded images is equal to the total images, show them all
if (++lcount >= icount) {
$('#gallery img').show();
}
}
);
});
或
最后,如果您只想等到整个页面加载完毕再显示它们,那么使用这个 jQuery:
jQuery(window).load(function($) {
$('#gallery img').show();
});
关于javascript - JS/CSS : Preload images from the HTML file while they are hidden,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24274275/