如果图像未加载,则执行某些操作(jquery)
我希望在访问者到达网站时淡入背景图像,但当他们已经在缓存中获得该图像时则不淡入淡出。类似的事情是:
- 检查背景图像是否已在缓存中。
- 如果是那就显示出来。
- 如果不是,则将其隐藏,并在加载时淡入。
使用 jQuery,我可以隐藏它,然后在加载时淡入:
$("#bkg img").hide();
$('#bkg img').load(function() {
$(this).fadeIn();
});
但是如何使此条件成为条件,以便仅在图像 isn 时才会发生尚未缓存?
当图像加载完成时,我在论坛上找到的所有内容都会触发。由于未加载,我怎样才能触发它?
感谢您的帮助, Lernz
@Sima 基于 其他线程的代码 我已经做到了以下几点 - 但它似乎没有任何效果。如果你能看到我哪里出错了那就太好了:
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();
}
});
});
I'm looking to fade in the background image when a visitor arrives at the site but not when they've already got that image in their cache. Something along the lines of this:
- Check if a background image is already in the cache.
- If it is then show it.
- If it isn't then hide it and when it loads, fade it in.
Using jQuery I can hide it and then fade it in when it loads:
$("#bkg img").hide();
$('#bkg img').load(function() {
$(this).fadeIn();
});
But how do I make this conditional so it only happens if the image isn't already cached?
Everything I've found on forums triggers when an image finishes loading. How can I get it to trigger because it isn't loaded?
Thanks for any help,
Lernz
@Sima Based on code from that other thread I've made it as far as the following - but it doesn't seem to be having any effect. If you can see where I'm going wrong that'd be great:
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();
}
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
您可以尝试:
https://developer.mozilla.org/en/DOM/HTMLImageElement
You can try:
https://developer.mozilla.org/en/DOM/HTMLImageElement
我认为这并不像看起来那么容易, 这里应该是一个解决方案..
I think that isn't as easy as it looks like, here should be a solution..