2016-11-28 35 views
0

我想获得整个屏幕高度,直到滚动发生(内容的总高度),这里是我尝试的代码,但我得到的值为0,对于如我的猜测是,整个屏幕的高度将更加然后1400px 如何得到确切高度如何从iframe或外部div获取滚动高度

<div id="sample"> 
    <iframe src="https://en.wikipedia.org/wiki/Main_Page" style="overflow:hidden;overflow-x:hidden;overflow-y:hidden;height:100%;width:100%;position:absolute;top:0x;left:0px;right:0px;bottom:0px" height="100%" width="100%" allowfullscreen id="frame" onload="myFunction()"> 
    </iframe> 
    <div style="display:block; clear:both;"></div> 
</div> 


    <script> 
    function myFunction() { 
     var elmnt = document.getElementById("sample"); 
     var y = elmnt.scrollHeight; 
     var x = elmnt.scrollWidth; 
     var sample = "Height: " + y + "px<br>Width: " + x + "px"; 
     alert(sample); 
    } 
    </script> 

回答

1

你得到height = 0因为iframe中的内容的高度不相关的父div元素,但在iframe的文档对象,因此您必须访问文档对象:

function myFunction() { 
     var elmnt = document.getElementById("frame"); 
     var win = elmnt.contentWindow; 
     var x = win.innerWidth; 
     var y = win.innerHeight; 
     var iframe = "Height: " + y + "px<br>Width: " + x + "px"; 
     alert(iframe); 
} 
更多 info on this error

Error: Permission denied to access property "innerWidth" 

检查MDN:

但是,这并不因为same-origin policy工作,你会得到下面的错误。

要访问DOM,您必须使用像phantomjs(基于Node.js)这样的无头浏览器来解析页面,这必须在服务器端完成,而且这是一种完全不同的方法,超出了本范围问题,但如果你想尝试,你可以找到很多examples