使用 Javascript 获取宽度

Get Width with Javascript

我是新手,所以要温柔。我在这里和互联网上的其他地方四处闲逛,但无法弄清楚。

  1. 我正在尝试确定 div 的宽度。
  2. 我希望以百分比表示。
  3. 我不想使用 JQuery(尝试学习 Javascript 可能)
  4. 我很失败。为什么 "theWidth"(下)不会产生任何结果?

感谢任何帮助。谢谢,dp

HTML

theWidth = document.getElementById("titleBG").style.width;
document.getElementById("titleBG").innerHTML = "Width = " + theWidth;
#titleBG{
  width:50%;
  height:50px;
  background-color:#ffcc33;
}
<div id="titleBG">
</div>

这里需要使用element.offsetWidth

获取百分比将无关紧要 - 它始终是您所在的当前视口的 50%。

如果您在页面上有一个包装 div 或某些其他元素可能会限制 div 的宽度,则情况可能并非如此,但您当前的代码就是这种情况。

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth

theWidth = document.getElementById("titleBG").offsetWidth;
document.getElementById("titleBG").innerHTML = "Width = " + theWidth;
#titleBG{
  width:50%;
  height:50px;
  background-color:#ffcc33;
}
<div id="titleBG">
</div>

获取元素大小(甚至位置)的最准确方法是使用

Element.getBoundingClientRect()

https://developer.mozilla.org/en-US/docs/Web/API/Element/getBoundingClientRect

window.getComputedStyle(element[, pseudoElt])

https://developer.mozilla.org/en-US/docs/Web/API/Window/getComputedStyle

https://developer.mozilla.org/en-US/docs/Web/API/Element/clientWidth(类似于getBoundingClientRect,只是returns一个整数)
https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth
https://developer.mozilla.org/en-US/docs/Web/API/Element/scrollWidth(获取总的可滚动宽度区域(即:当元素溢出时))

您可以通过获取元素的父级 (GBCR) 宽度的相同方式计算百分比,并使用 Number( (100/(parentWidth/width)).toFixed(3) )

计算 %

var title = document.getElementById("titleBG");
var width = title.getBoundingClientRect().width;
var pwidth = title.parentNode.getBoundingClientRect().width;

title.innerHTML = "Computed Width= "+ window.getComputedStyle(title, null).width +"<br>"+
  " GBCRWidth= " + width +"<br>"+
  " Perc= "+ Number((100/(pwidth/width)).toFixed(3)) +"%";
#titleBG{
  width:50%;
  height:50px;
  background-color:#ffcc33;
}
<div id="titleBG"></div>