2017-04-13 102 views
1
var div= document.getElementById('foo'); 
console.log(div); 
console.log(div.scrollHeight); 

当我点击控制台中第一个日志返回的div的DOM时,它的scrollHeight是x,而第二个日志打印出y。 x!= y,JS返回div的高度不正确

+2

内容仍在加载/渲染? – epascarello

+0

但我在div.scrollheight之前记录div,在div中它是正确的值。也许它仍然是这样,如何解决它在纯JavaScript/angularjs? – user3761308

+0

如果你只是想得到一个元素的高度,你可以使用“div.clientHeight”,它应该给你。 – garglblarg

回答

0

使用jQuery加载得到一个div的高度。

alert($("divId").height()); 

或JavaScript

var clientHeight = document.getElementById('divId').clientHeight; 

var offsetHeight = document.getElementById('divId').offsetHeight; 
+1

更改'var div = document.getElementById('foo'); console.log(div.scrollHeight);'to'console.log(document.getElementById('foo')。scrollHeight)'输出正确的值。 – user3761308

1

我可以看到,在这里我越来越完美了。你可以给你的代码,你已经尝试到目前为止?

<!DOCTYPE html> 
 
<html> 
 
<head> 
 
\t <title></title> 
 

 
</head> 
 
<body> 
 
\t <div id="foo">HELLO WORLD!!!</div> 
 
\t <script type="text/javascript"> 
 

 

 
\t var div= document.getElementById('foo'); 
 
\t console.log(div); 
 
\t console.log(div.scrollHeight); 
 
\t console.log(div.clientHeight); 
 
\t console.log(div.offsetHeight); 
 
\t </script> 
 
</body> 
 
</html>

0

使用.load要等到该元素在DOM

$('#foo').load(function(){ 
    // your code to find height 
    $('#foo').height() 
    });