2016-07-21 103 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;