开发者

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

Here is my code. This centers images vertically with the class productImage. I have a bunch of images within the class.开发者_Go百科 This works fine in chrome. but itermittently in ie and firefox. I can't figure out what's going on. I think it has something to do with when the image is getting loaded. I though by binding the load event to each image, it would always wait until each image is loaded until it fires, but it is not ... sometimes. Can anyone shed some light on this?

$('img.productImage').each(function(){
var jproductImage = $(this);

jproductImage.load(function(){
    jproductImage.css({
    'margin-left' : -jproductImage.width()/2 + 'px',
    'margin-top': -jproductImage.height()/2 + 'px'
    });
});

});

Thanks, Matt


It could be that the images are getting cached by the browser, thereby preventing the .load event from firing. You can circumvent this problem by testing for the .complete property on each image, and where it is set, manually triggering the .load event:

$('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");  
});

Also, your outer .each is a bit redundant. The above is all that is needed.


.load is simply unreliable on images, crossbrowser. Firefox will not fire it when loading the image from cache, for instance. Check out the jQuery docs for .load.

One section reads:

Caveats of the load event when used with images

A common challenge developers attempt to solve using the .load() shortcut is to execute a function when an image (or collection of images) have completely loaded. There are several known caveats with this that should be noted. These are:

It doesn't work consistently nor reliably cross-browser
It doesn't fire correctly in WebKit if the image src is set to the same src as before
It doesn't correctly bubble up the DOM tree
Can cease to fire for images that already live in the browser's cache

In my experience, creating an image object, binding a handler to it's load event, and then setting the src works more reliably if that strategy is possible.


What's that - before jproductImage ?

$('img.productImage').each(function(){
    var jproductImage = $(this);

    jproductImage.css({
    'margin-left' : '-'+jproductImage.width()/2 + 'px',
    'margin-top': '-'+jproductImage.height()/2 + 'px'
    });

});

Is this what are you looking for?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜