javascript 通过 attributes.getNamedItem 获取元素的实际宽度/高度值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/5267790/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 16:35:34  来源:igfitidea点击:

Getting actual widh/height values of element via attributes.getNamedItem

javascriptdomheightwidth

提问by Alper


i am tring to get the width/height values of an element in dom tree (HTML page) and i am using below method:


我正在尝试获取 dom 树(HTML 页面)中元素的宽度/高度值,我正在使用以下方法:

var event = e || window.event;
var target = event.target || event.srcElement;

var event = e || window.event;
var target = event.target || event.srcElement;

i am getting id and class information by using

我正在通过使用获取 id 和 class 信息

var classinfo = target.attributes.getNamedItem("class").nodeValue;
var idinfo = target.attributes.getNamedItem("id").nodeValue;

var classinfo = target.attributes.getNamedItem("class").nodeValue;
var idinfo = target.attributes.getNamedItem("id").nodeValue;

但正如你所猜到的,任何元素都不必有 id 和/或类节点,所以我无法检查 width="..px"width="..px"节点值或getElementByIdgetElementById方法


结果,有没有办法通过使用获取节点元素的宽度和高度值getNamedItemgetNamedItem方法/或您可以建议的任何其他方法。


NOTE:注意:我需要获得真实的宽度和高度,而不是 css 或内联,因为 css 中的宽度可能是 60%,但它呈现为 100px ......


提前致谢。

回答by kennebec

element.offsetWidth, element.offsetHeight: overall size of the containing box in pixels

element.offsetWidth, element.offsetHeight:包含框的整体大小(以像素为单位)

element.clientHeight, element.clientWidth: content dimensions

element.clientHeight, element.clientWidth: 内容尺寸

These are read onlyproperties, and always return the current rendered values.

这些是只读属性,并且始终返回当前呈现的值。

(You need to assign a style property in the element or in a stylesheet to setmost elements onscreen height and width.)

(您需要在元素或样式表中分配样式属性以设置屏幕上大多数元素的高度和宽度。)