gpt4 book ai didi

javascript - 如何通过javascript获取元素宽度

转载 作者:太空宇宙 更新时间:2023-11-04 10:09:52 25 4
gpt4 key购买 nike

查找宽度的 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com