遇到 $('img').load(function(){something} 的问题;在IE和火狐中

Having Problems with $('img').load(function(){something}); in ie and firefox

本文关键字:问题 IE 火狐 function img load 遇到 something      更新时间:2023-09-26

这是我的代码。这会将图像与类 productImage 垂直居中。我在班上有一堆图像。这在铬中工作正常。但在IE和Firefox中是无情的。我不知道发生了什么。我认为这与加载图像的时间有关。我虽然通过将加载事件绑定到每个图像,它总是等到每个图像被加载直到它触发,但它不是......有时。谁能对此有所了解?

$('img.productImage').each(function(){
var jproductImage = $(this);
jproductImage.load(function(){
    jproductImage.css({
    'margin-left' : -jproductImage.width()/2 + 'px',
    'margin-top': -jproductImage.height()/2 + 'px'
    });
});
});

谢谢马 特

可能是图像被浏览器缓存,从而阻止.load事件触发。可以通过测试每个映像上的 .complete 属性以及设置属性的位置(手动触发 .load 事件(来规避此问题:

$('img.productImage').one("load",function() {
    $(this).css({
        'margin-left': $(this).width() / 2 + 'px',
        'margin-top': $(this).height() / 2 + 'px'
    });
}).each(function() {
    if(this.complete) $(this).trigger("load");  
});

此外,您的外部.each有点多余。以上就是所有需要的。

.load 在图像上根本不可靠,跨浏览器。 例如,Firefox 在从缓存加载图像时不会触发它。查看 .load 的 jQuery 文档。

其中一节内容如下:

与图像一起使用时加载事件的注意事项

开发人员尝试使用 .load(( 快捷方式解决的一个常见挑战是在图像(或图像集合(完全加载时执行函数。有几个已知的警告应该注意。这些是:

它不能始终如一地工作,也不能可靠地跨浏览器工作
如果映像 src 设置为与之前相同的 src,则它不会在 WebKit 中正确触发
它没有正确地冒泡 DOM 树
可以停止为浏览器缓存中已存在的图像触发

根据我的经验,创建一个图像对象,将处理程序绑定到它的加载事件,然后设置 src 如果该策略可行,则工作更可靠。

在jproductImage之前-是什么?

$('img.productImage').each(function(){
    var jproductImage = $(this);
    jproductImage.css({
    'margin-left' : '-'+jproductImage.width()/2 + 'px',
    'margin-top': '-'+jproductImage.height()/2 + 'px'
    });
});

这是你要找的吗?