[英]How to get width of element with javascript?
I am trying to compare width of one element with "100%" with the below code. 我正在尝试使用以下代码将一个元素的宽度与“ 100%”进行比较。 I wrote this code but did not work.
我写了这段代码,但是没有用。 Width of element is
100%
. 元素的宽度为
100%
。 Please advice 请指教
if (document.getElementsByClassName("progress-bar")[0].offsetWidth ==="100%") {
clearInterval(r1);
clearInterval(r2);
clearInterval(r3);
}
Your code is working correctly, but offsetWidth
returns the physical pixel width of the element on the screen. 您的代码正常工作,但是
offsetWidth
返回屏幕上元素的物理像素宽度。 Since you're doing a strict equality comparison using ===
, the if()
block never evaluates to true; 由于您使用
===
进行严格的相等比较,因此if()
块永远不会求值为true; offsetWidth
returns an integer to start, and will never append the %
value. offsetWidth
返回一个整数开始,并且永远不会附加%
值。
For example, see this jsFiddle demo -- the <input />
's value becomes an integer. 例如,请参见此jsFiddle演示 -
<input />
的值变为整数。
If you absolutely need to have the width as a percentage value, you'll need to access the element's CSS definitions using the HTMLElement.style
property as follows: 如果绝对需要使用宽度作为百分比值,则需要使用
HTMLElement.style
属性访问元素的CSS定义,如下所示:
document.getElementsByClassName("progress-bar")[0].style.width;
Ultimately, your if()
block will become: 最终,您的
if()
块将变为:
if( document.getElementsByClassName("progress-bar")[0].style.width == '100%' )
{
clearInterval(r1);
clearInterval(r2);
clearInterval(r3);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.