简体   繁体   中英

CSS styles are applied and displayed but JS doesn't recognize the CSS applied

Something weird is going on and I'm not sure what it is. I created a bunch of elements and I want to get the width of my progress bar so I can work with it in my JS code.

In my JS I do:

var bar = document.getElementById('progressBar');
console.log(bar.style.width); //empty string

however in my CSS I have

#progressBar{
  width: 600px;
  border: 2px solid black;
}

and I can clearly see the 600px container and the border around it in the browser, but for some reason, JS doens't know about these CSS settings.

Any ideas what the problem might be?

EDIT: This is different from the suggested duplicate - the problem is not that I don't know how to the get the value, the problem is that the style.value doesn't get me what I expect.

That is correct behaviour.

The style property of a DOMElement is responsible for inline styles, not the actual computed values. To get the width, use getClientRects or getBoundingClientRect .

eg

 var bar = document.querySelector('.bar'); console.log(bar.style.width); // empty string console.log(bar.getBoundingClientRect().width); // 100px 
 .bar { width: 100px; height: 20px; background: blue; } 
 <div class='bar'></div> 

You may also be interested in: How do I get a computed style?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM