2016-11-28 74 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