如果高度大于宽度,则为动态图像添加类,但仅在刷新页面时有效

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

本文关键字:刷新 有效 图像 大于 高度 如果 动态 添加      更新时间:2023-09-26

我有这样的代码,当图像加载到我们的应用程序中时,当高度大于宽度时,添加一个类来增加边距。但是,除非刷新页面,否则函数不会执行。任何想法&这看起来对吗?谢谢

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);
}
};

看起来clearInterval(wait);是阻止计时器运行的原因。