[英]How to get document height and width without using jquery
如何在純javascript中獲取文檔高度和寬度,即不使用jquery 。
我知道$(document).height()
和$(document).width()
,但我想在javascript中執行此操作。
我的意思是頁面的高度和寬度。
var height = document.body.clientHeight;
var width = document.body.clientWidth;
檢查:這篇文章以獲得更好的解釋。
即使是在http://www.howtocreate.co.uk/tutorials/javascript/browserwindow上給出的最后一個例子也不能在 Quirks 模式下工作。 比我想象的更容易找到,這似乎是解決方案(從最新的 jquery 代碼中提取):
Math.max(
document.documentElement["clientWidth"],
document.body["scrollWidth"],
document.documentElement["scrollWidth"],
document.body["offsetWidth"],
document.documentElement["offsetWidth"]
);
只需將寬度替換為“高度”即可獲得高度。
這是一個跨瀏覽器的解決方案:
var w = window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth;
var h = window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight;
您應該使用getBoundingClientRect
因為它通常可以跨瀏覽器工作,並在邊界矩形上為您提供亞像素精度。
elem.getBoundingClientRect()
在沒有 jQuery 的情況下獲取文檔大小
document.documentElement.clientWidth
document.documentElement.clientHeight
如果您需要屏幕尺寸,請使用它
screen.width
screen.height
這應該適用於所有瀏覽器/設備:
function getActualWidth()
{
var actualWidth = window.innerWidth ||
document.documentElement.clientWidth ||
document.body.clientWidth ||
document.body.offsetWidth;
return actualWidth;
}
你也可以試試:
document.body.offsetHeight
document.body.offsetWidth
如果要獲取頁面的全寬,包括溢出,請使用document.body.scrollWidth
。
window
是整個瀏覽器的應用程序窗口。 document
是顯示的實際加載的網頁。
window.innerWidth
和window.innerHeight
將考慮滾動條,這可能不是您想要的。
document.documentElement
是沒有頂部滾動條的完整網頁。 document.documentElement.clientWidth
返回沒有 y 滾動條的文檔寬度大小。 document.documentElement.clientHeight
返回沒有 x 滾動條的文檔高度大小。
如何很容易地找出文檔的寬度和高度?
在 HTML 中<span id="hidden_placer" style="position:absolute;right:0;bottom:0;visibility:hidden;"></span>
在javascript中
var c=document.querySelector('#hidden_placer');
var r=c.getBoundingClientRect();
r.right=document width
r.bottom=document height`
如果需要,您可以在每個窗口調整大小事件上更新它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.