jQuery使用完全回调加载图像
我看到Stephen Rushing在哪里发布了一个加载程序,但我不知道如何传递选择器和参数 我想我还需要一个jQuery使用完全回调加载图像,jquery,image,Jquery,Image,我看到Stephen Rushing在哪里发布了一个加载程序,但我不知道如何传递选择器和参数 我想我还需要一个completeCallback和errorCallback函数 function imgLoad(img, completeCallback, errorCallback) { if (img != null && completeCallback != null) { var loadWatch = setInterval(watch, 500
completeCallback
和errorCallback
函数
function imgLoad(img, completeCallback, errorCallback) {
if (img != null && completeCallback != null) {
var loadWatch = setInterval(watch, 500);
function watch() {
if (img.complete) {
clearInterval(loadWatch);
completeCallback(img);
}
}
} else {
if (typeof errorCallback == "function") errorCallback();
}
}
// then call this from anywhere
imgLoad($("img.selector")[0], function(img) {
$(img).fadeIn();
});
HTML:
如果您希望在显示之前加载,可以将其进行大幅剪裁,如下所示:
$(document).ready(function() {
var newImage = "images/002.jpg"; //Image name
$("a.tnClick").click(function() {
$("#myImage").hide() //Hide it
.one('load', function() { //Set something to run when it finishes loading
$(this).fadeIn(); //Fade it in when loaded
})
.attr('src', newImage) //Set the source so it begins fetching
.each(function() {
//Cache fix for browsers that don't trigger .load()
if(this.complete) $(this).trigger('load');
});
});
});
.one()
调用确保.load()只触发一次,因此不会出现重复的淡入淡入。最后的.each()
是因为一些浏览器没有为从缓存中获取的图像触发加载
事件,这也是您发布的示例中的轮询所要做的。试试这个吗
doShow = function() {
if ($('#img_id').attr('complete')) {
alert('Image is loaded!');
} else {
window.setTimeout('doShow()', 100);
}
};
$('#img_id').attr('src', 'image.jpg');
doShow();
似乎上面的方法适用于所有地方…在使用图像加载事件时需要小心,因为如果在浏览器的缓存IE中找到图像,并且(我被告知)Chrome不会按预期触发事件 因为我必须自己面对这个问题,所以我通过检查DOM属性complete(据说在大多数主流浏览器中都能工作)来解决这个问题:如果等于true,我就取消绑定之前绑定的“load”事件。见示例:
$("#myimage").attr("src","http://www.mysite.com/myimage.jpg").load(doSomething);
if ($("#myimage").get(0).complete) {
// already in cache?
$("#myimage").unbind("load");
doSomething();
}
希望这能有所帮助我想要这个功能,而且肯定不想在页面呈现时加载所有图像。我的图片在AmazonS3上,有一个很大的照片库,这将是很多不必要的请求。我创建了一个快速jQuery插件来处理它:
因此,基本上,每当用户单击表示一组图片的缩略图时,我都会在该时间点加载其他图像。回调允许我在图像加载后更改css 你想做什么,在显示之前预装你的图片?实际上我只是想让它淡入。。单击图像时,将其显示设置为“无”并加载。加载完成后,淡入.oooh“针对不触发.load()的浏览器的缓存修复”,这是我的问题(在阅读该文章后),你知道哪些浏览器不支持.load吗?@FFish-欢迎!回答你的另一个问题:我知道的浏览器是Opera、Firefox、IE……但这可能不是全部列表。这就是我想要的!它也适用于Android浏览器。
doShow = function() {
if ($('#img_id').attr('complete')) {
alert('Image is loaded!');
} else {
window.setTimeout('doShow()', 100);
}
};
$('#img_id').attr('src', 'image.jpg');
doShow();
$("#myimage").attr("src","http://www.mysite.com/myimage.jpg").load(doSomething);
if ($("#myimage").get(0).complete) {
// already in cache?
$("#myimage").unbind("load");
doSomething();
}
$("#image-1").loadImage('/path/to/new/image.jpg',function(){
$(this).css({height:'120px'});//alter the css styling after the image has loaded
});