簡體   English   中英

如何在不使用 jquery 的情況下獲取文檔的高度和寬度

[英]How to get document height and width without using jquery

如何在純中獲取文檔高度和寬度,即不使用
我知道$(document).height()$(document).width() ,但我想在中執行此操作。

我的意思是頁面的高度和寬度。

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.innerWidthwindow.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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM