我想做的是:
$("img").bind('load', function() {
// do stuff
});
但是当图像从缓存中加载时,load事件不会触发。jQuery文档建议用一个插件来解决这个问题,但它不起作用
我想做的是:
$("img").bind('load', function() {
// do stuff
});
但是当图像从缓存中加载时,load事件不会触发。jQuery文档建议用一个插件来解决这个问题,但它不起作用
当前回答
你真的必须用jQuery来做吗?你也可以将onload事件直接附加到你的图像上;
<img src="/path/to/image.jpg" onload="doStuff(this);" />
它将在每次图像加载时触发,无论是否从缓存中加载。
其他回答
如果src已经设置,则在绑定事件处理程序之前,事件就会在缓存的情况下触发。为了解决这个问题,你可以循环检查和触发基于.complete的事件,就像这样:
$("img").one("load", function() {
// do stuff
}).each(function() {
if(this.complete) {
$(this).load(); // For jQuery < 3.0
// $(this).trigger('load'); // For jQuery >= 3.0
}
});
注意从.bind()到.one()的变化,因此事件处理程序不会运行两次。
我找到了一个解决方案https://bugs.chromium.org/p/chromium/issues/detail?id=7731#c12 (此代码直接取自注释)
var photo = document.getElementById('image_id');
var img = new Image();
img.addEventListener('load', myFunction, false);
img.src = 'http://newimgsource.jpg';
photo.src = img.src;
我有这个问题与IE的e.target.width将是未定义。加载事件会发生,但我无法在IE中获得图像的尺寸(chrome + FF工作)。
结果你需要寻找e.currentTarget.naturalWidth & e.currentTarget.naturalHeight。
再说一次,IE有自己的(更复杂的)做事方式。
我的简单解决方案,它不需要任何外部插件,对于常见情况应该足够了:
/**
* Trigger a callback when the selected images are loaded:
* @param {String} selector
* @param {Function} callback
*/
var onImgLoad = function(selector, callback){
$(selector).each(function(){
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
});
};
像这样使用它:
onImgLoad('img', function(){
// do stuff
});
例如,要在你的图像加载淡出,你可以做:
$('img').hide();
onImgLoad('img', function(){
$(this).fadeIn(700);
});
或者作为替代,如果你喜欢jquery插件类的方法:
/**
* Trigger a callback when 'this' image is loaded:
* @param {Function} callback
*/
(function($){
$.fn.imgLoad = function(callback) {
return this.each(function() {
if (callback) {
if (this.complete || /*for IE 10-*/ $(this).height() > 0) {
callback.apply(this);
}
else {
$(this).on('load', function(){
callback.apply(this);
});
}
}
});
};
})(jQuery);
并这样使用它:
$('img').imgLoad(function(){
// do stuff
});
例如:
$('img').hide().imgLoad(function(){
$(this).fadeIn(700);
});
只需要在img对象定义后的另一行中重新添加src参数。这将欺骗IE触发lad事件。它很丑,但这是我迄今为止发现的最简单的解决方法。
jQuery('<img/>', {
src: url,
id: 'whatever'
})
.load(function() {
})
.appendTo('#someelement');
$('#whatever').attr('src', url); // trigger .load on IE