Javascript 使用属性集获取实际加载图像的宽度和高度

Javascript 使用属性集获取实际加载图像的宽度和高度,javascript,jquery,html,Javascript,Jquery,Html,我有一个设置了宽度和高度的图像标签: <img src='<%#Eval("ImageLocation").ToString().TrimStart(new char[]{'~'}).ToLower() %>' width="147px" height="147px" /> 'width=“147px”height=“147px”/ 现在有些图像不是147x147,这意味着它们看起来不好,所以我想在加载后检查图像的宽度和高度。我试着在img上添加onload <

我有一个设置了宽度和高度的图像标签:

<img src='<%#Eval("ImageLocation").ToString().TrimStart(new char[]{'~'}).ToLower() %>' width="147px" height="147px" />
'width=“147px”height=“147px”/
现在有些图像不是147x147,这意味着它们看起来不好,所以我想在加载后检查图像的宽度和高度。我试着在img上添加onload

<img src='<%#Eval("ImageLocation").ToString().TrimStart(new char[]{'~'}).ToLower() %>' width="147px" height="147px" onload="checkOrientation(this);"/>
'width=“147px”height=“147px”onload=“检查方向(此);”/>
在函数中,我做:

 function checkOrientation(el) {
           alert(el.width + "    " + el.height);

           if (el.height < el.width)
               $(el).removeAttr('height');
           else
               $(el).removeAttr('width');
       }
功能检查方向(el){
警告(标高宽度+标高高度);
如果(标高高度<标高宽度)
$(el).removeAttr('高度');
其他的
$(el).removeAttr('宽度');
}
但这总是会把147还给你,即使照片不是147


如何获取实际加载图像的宽度和高度?

如果要获取原始宽度和高度,则需要编写如下函数。其想法是将src分配给新的img元素,并检查宽度和高度。因为您已经为当前img指定了一些宽度和高度

  function checkOrientation(el) {
        var image = new Image();
        image.src = el.attr('src');
        image.onload = function () {
        this.height;
        this.width;
        alert(this.width + "    " + this.height);
        if (this.height < this.width)
           $(el).removeAttr('height');
       else
           $(el).removeAttr('width');
        } 
   }
功能检查方向(el){
var image=新图像();
image.src=el.attr('src');
image.onload=函数(){
这是身高;
这是宽度;
警报(this.width+“”+this.height);
如果(此高度<此宽度)
$(el).removeAttr('高度');
其他的
$(el).removeAttr('宽度');
} 
}

您将宽度和高度值传递为静态值,即“147px”,因此函数会向147发出警报