查找宽度的 JavaScript 代码是什么?
(我想要获取宽度 .FixedBox
没有 jquery 的 javascript,但我的代码不起作用。)
alert(document.getElementsByClassName('FixedBox').offsetWidth);
<div class="FixedBox">
The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present, if rendered) and the element CSS width.
</div>
最佳答案
Document.getElementsByClassName()
返回 NodeList 你需要从集合中获取元素才能得到 offsetWidth
属性。还将它们放在窗口加载回调中,以便仅在加载元素后执行。
window.onload = function() {
var ele = document.getElementsByClassName('FixedBox');
alert(ele.length ? ele[0].offsetWidth : 'no elements with the class');
}
<div class="FixedBox">
The HTMLElement.offsetWidth read-only property returns the layout width of an element. Typically, an element's offsetWidth is a measurement which includes the element borders, the element horizontal padding, the element vertical scrollbar (if present,
if rendered) and the element CSS width.
</div>
关于javascript - 如何通过javascript获取元素宽度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37700822/