我希望在访问者到达网站时淡入背景图像,但当他们已经在缓存中获得该图像时则不淡入淡出。类似这样的事情:
- 检查背景图像是否已在缓存中。
- 如果是,则显示出来。
- 如果不是,则将其隐藏,加载后淡入。
使用 jQuery,我可以隐藏它,然后在加载时淡入它:
$("#bkg img").hide();
$('#bkg img').load(function() {
$(this).fadeIn();
});
但是我该如何设置这个条件,以便只有在图像尚未已缓存时才会发生?
当图像加载完成时,我在论坛上找到的所有内容都会触发。由于未加载,我怎样才能触发它?
感谢您的帮助, 伦茨
@Sima 基于 that other thread 中的代码我已经做到了以下几点 - 但似乎没有任何效果。如果您能看到我哪里出错了,那就太好了:
var storage = window.localStorage;
if (!storage.cachedElements) {
storage.cachedElements = "";
}
function logCache(source) {
if (storage.cachedElements.indexOf(source, 0) < 0) {
if (storage.cachedElements != "")
storage.cachedElements += ";";
storage.cachedElements += source;
}
}
function cached(source) {
return (storage.cachedElements.indexOf(source, 0) >= 0);
}
var plImages;
//On DOM Ready
$(document).ready(function() {
plImages = $("#fundo-1 img");
//log cached images
plImages.bind('load', function() {
logCache($(this).attr("src"));
});
//display cached images
plImages.each(function() {
var source = $(this).attr("src")
if (!cached(source)) {
$(this).hide().fadeIn();
}
});
});
最佳答案
你可以尝试:
if(!$('#bkg img')[0].complete) {
$('#bkg img').hide().load(function () {
$(this).fadeIn();
});
}
关于jquery - 如果图像未加载,则执行某些操作(jquery),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8932153/