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

标签 javascript jquery html css

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

相关文章:

javascript - iframe 手机问题

javascript - jQuery 在 div > divs > a 中委托(delegate)也是 :(

javascript - 从映射数组中获取元素

javascript - 有很多页面的分页

jquery - 给定一组 div,如何确定连续的最后一个

javascript - 如何使我的 javascript slider 响应更快(更快)?

jquery - 流沙元素在初始加载时看起来不合适

javascript - 如何根据下拉值更新div文本?

html - HTML5 中的交互式平面图

html - 创建以相同宽度向左浮动的 div 框的问题