简体   繁体   English

如何从image标签获取width和height属性?

[英]How to get the width and height attributes from the image tag?

I have the following image tag 我有以下图像标签

<img class="someclass" src="somesrc" width="220" height="165" />

The browser is displaying the image with its original width and height which is 480x360 浏览器正在显示原始宽度和高度为480x360

I want to get the image width and height attributes from the image tag which should return 220 and 165 我想从图像标签获取图像的宽度和高度属性,该属性应返回220 and 165

I have tried the following 我尝试了以下

var img = document.getElementsByClassName('someclass');
console.log(img.clientWidth);
console.log($('.someclass').attr('width'));

But it returns me undefined . 但这使我undefined

The following code returns me the actual width and height of the image. 以下代码返回了图像的实际宽度和高度。 which is 480 480

$('.someclass').width();

Is there any way that it should return the 220 and 165 ? 有什么办法可以返回220 and 165吗?

You need to get the width attribute of a single element not a nodeList as you were returning. 您需要获取单个元素的宽度属性,而不是返回时的nodeList。

Try this... 尝试这个...

var element = document.querySelector('.someclass');
console.log(element.getAttribute('width')); //220
console.log(element.getAttribute('height')); //165

Thanks to all for your help. 感谢大家的帮助。 But I have found the solution. 但是我找到了解决方案。 The following code works for me. 以下代码对我有用。

$('img.someclass).load(function(){
  var width = $(this).attr('width');
  var height = $(this).attr('height');
  if(width != 'undefined') {
     $(this).css('width', width);
  }
  if(height != 'undefined') {
    $(this).css('height', height);
  }
});
var x = document.createElement("IMG");
x.setAttribute("src", "path/here");
x.setAttribute("width", "220");
x.setAttribute("height", "165");
document.getElementById("SomeID").appendChild(x);

Give it some ID and this should work if you want to use JS. 给它一些ID,如果您想使用JS,这应该可以工作。

Try 尝试

var img = document.getElementsByClassName('someclass')[0];
var width = img.width;
var height = img.height

and in case you want to set new values just do: 如果您想设置新值,请执行以下操作:

img.width = yourvalue;
img.height = yourvalue;

it works fine, so plz don't downvote people for no reason 它工作正常,所以请不要无故拒绝人们

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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