簡體   English   中英

使用document.getElementById()。style.height javascript從CSS獲取價值

[英]get value from css using document.getElementById().style.height javascript

請深入了解這個謎題。

我正在嘗試通過div框獲取高度值

var high = document.getElementById("hintdiv").style.height; 
alert(high);

如果該屬性包含在div標記中,則可以很好地獲得此值,但是如果該屬性在css部分中定義,則它將返回一個空白值。

很好,它將100px顯示為一個值。 可以訪問該值。

<div id="hintdiv" style="height:100px; display: none;">
.
.
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

這不好,它顯示一個空的警報屏幕。 值實際上是0。

#hintdiv
{
height:100px
display: none; 
}

<div id="hintdiv">
.
.
var high = document.getElementById("hintdiv").style.height; 
    alert(high); 

但是無論是在標記中還是在css部分中,我都可以訪問/更改“ display:none”屬性。 兩種屬性定義方法(在標簽內部或在css部分中)都可以正確顯示div框。

我還嘗試通過其他變體來訪問值,但是沒有運氣

document.getElementById("hintdiv").style.height.value  ----> undefined
document.getElementById("hintdiv").height ---->undefined
document.getElementById("hintdiv").height.value  ----> error, no execution

有什么辦法嗎?

TIA。

這是因為,當您使用document.getElementById("hintdiv").style.height; 您正在訪問標記的style屬性。 如果該屬性不存在,那么您將不會獲得任何值。

相反,您應該在IE中使用currentStyle對象,並在其余的Web瀏覽器中使用getComputedStyle()函數。

您的CSS語法有誤,應為height:100px; 而不是height:100px 注意分號。

您應該考慮使用usign jQuery ...它將簡化為$('#hintDiv')。height(),並將始終返回div的實際寬度。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM