2016-07-21 104 views
1

Fiddle無法獲取節點

 window.addEventListener("resize", getSize); 

      function getSize(){ 
       var node = document.getElementById('sample'); 
       var height = node.style.height; 
       console.log('height: ', height);//expect 100px, get nothing 
      } 

    #sample { 
    padding: 20px; 
    height: 100px; 
    overflow-y: auto; 
    border: solid blue; 
    margin: 10px 300px 10px 25px; 
    position: 'relative' 

} 

node.style.height的高度總是空/空。請注意,我將高度設置爲100px。爲什麼?我怎樣才能獲得節點的CSS高度?

+0

使用'節點。 offsetHeight'。 –

+0

或node.clientHeight – n0m4d

+0

請注意,您仍然需要使用'node.style.height ='1000px';'來設置值。設置'offsetHeight'不起作用。 –

回答

1

要獲得元素的高度(無邊距),請使用element.offsetHeight

要直接訪問CSS屬性,你必須使用getComputedStyle

const node = document.getElementById('lorem'); 
const styles = getComputedStyle(node); 
const height = styles.height;