如何从图像标签获取宽度和高度属性?
问题描述:
我有图像标记以下如何从图像标签获取宽度和高度属性?
<img class="someclass" src="somesrc" width="220" height="165" />
的浏览器,其原有的宽度和高度,这是480x360
显示图像我想要得到的图像宽度和高度从图像标签的属性即应返回220 and 165
我曾尝试以下
var img = document.getElementsByClassName('someclass');
console.log(img.clientWidth);
console.log($('.someclass').attr('width'));
但它返回我undefined
。
以下代码返回图像的实际宽度和高度。这是480
$('.someclass').width();
有什么办法,它应该返回220 and 165
?
答
感谢大家的帮助。但我找到了解决办法。 以下代码适用于我。
$('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);
给它一些ID,这应该工作,如果你想使用JS。
答
您需要在返回时获取单个元素的width属性而不是nodeList。
尝试......
var element = document.querySelector('.someclass');
console.log(element.getAttribute('width')); //220
console.log(element.getAttribute('height')); //165
答
尝试
var img = document.getElementsByClassName('someclass')[0];
var width = img.width;
var height = img.height
,并在情况下,你要设置新的价值只是做:
img.width = yourvalue;
img.height = yourvalue;
它工作得很好,所以PLZ不要没有理由让人无望地投降
+0
你误读了他在属性值之后的问题,而不是渲染的宽度/高度 – Zinc
'img'是'HTMLCollection',而不是元素 – MysterX
'document.getElementsByClassName( 'SomeClass的')[0]'' –
$(”。SomeClass的 ')。ATTR(' 宽度 ')'应当' ve worked fine – adeneo