简体   繁体   中英

adding class for a dynamic image if the height is greater than the width, but only works when refreshing the page

I have this code for when an image loads in our app and then when the height is greater than the width, add a class to bump up the margin. However unless you refresh the page, the function doesn't get executed. Any ideas & does this seem right? Thank you

window.onload = function() {
 getImageSize($('#productImage'), function(width, height){
 $('.product-info').console.log(width + ',' + height);
});

function getImageSize(img, callback) {
var $img = $(img);

var wait = setInterval(function() {
    var w = $img[0].naturalWidth,
        h = $img[0].naturalHeight;
    if (w && h) {
        clearInterval(wait);
        callback.apply(this, [w, h]);

    }
  if (h > w) {
   $("#productImage").addClass("image-margin"); 
  }
}, 30);

}
};

Looks like clearInterval(wait); is the one preventing your timer to run.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM