[英]How to get the width and height attributes from the image tag?
我有以下图像标签
<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
吗?
您需要获取单个元素的宽度属性,而不是返回时的nodeList。
尝试这个...
var element = document.querySelector('.someclass');
console.log(element.getAttribute('width')); //220
console.log(element.getAttribute('height')); //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,这应该可以工作。
尝试
var img = document.getElementsByClassName('someclass')[0];
var width = img.width;
var height = img.height
如果您想设置新值,请执行以下操作:
img.width = yourvalue;
img.height = yourvalue;
它工作正常,所以请不要无故拒绝人们
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.