[英]CSS styles are applied and displayed but JS doesn't recognize the CSS applied
發生了奇怪的事情,我不確定這是什么。 我創建了一堆元素,我想獲得進度條的寬度,以便可以在JS代碼中使用它。
在我的JS中,我這樣做:
var bar = document.getElementById('progressBar');
console.log(bar.style.width); //empty string
但是在我的CSS中
#progressBar{
width: 600px;
border: 2px solid black;
}
而且我可以在瀏覽器中清楚地看到600px容器及其周圍的邊框,但是由於某些原因,JS並不了解這些CSS設置。
任何想法可能是什么問題?
編輯:這與建議的重復項不同-問題不是我不知道如何獲取值,問題是style.value
不能得到我期望的值。
這是正確的行為。
DOMElement的style
屬性負責inline
樣式,而不是實際的計算值。 要獲取寬度,請使用getClientRects
或getBoundingClientRect
。
例如
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>
您可能也對以下內容感興趣: 如何獲得計算樣式?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.