window.innerHeight和document.documentElement.clientHeight區別


今天有人問我這個問題,做了個小例子來記錄一下子。

首先這兩個都是獲取可視區域的高度,那他們有什么區別呢

1.window.innerHeight屬於BOM(瀏覽器對象模型),而document.documentElement.clientHeight則屬於文檔對象模型

2.window.innerHeight獲取的高度包含橫向滾動條,而document.documentElement.clientHeight不包含橫向滾動條

做了一個小示例

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <style>
        html,body{
            margin: 0;
            padding: 0;
            height: 100%;
            width: 100%;
        }
        .box{
            height: 100%;
            width: 100%;
            background-color: red;
        }
    </style>
</head>
<body>
<div class="box"></div>
<script>
    console.log('innerHeight:'+ window.innerHeight)
    console.log('clientHeight:'+ document.documentElement.clientHeight)
</script>
       
</body>
</html>

此時運行打印結果:

innerHeight:760
clientHeight:760

可以看到沒有橫向滾動條時兩者是相等的

現在我們將上面代碼中box的寬度改為120%,使之出現橫向滾動條

再看看結果

innerHeight:760
clientHeight:743

可以看到document.documentElement.clientHeight的高度少了一些,原因就是document.documentElement.clientHeight不包括橫向滾動條


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM