如何获取隐藏div元素的高度

父级元素指定高设置超出部分为scroll 子元素 超出父级元素的高 将页面滚动条设置不显示 现需求求出隐藏部分的高度
不用 滚动条事件及相应的属性如何能获取到隐藏元素的高度

阅读 4.9k
3 个回答

使用Element.getBoundingClientRect()来获取相对于viewport的位置,
2个元素top位置的差就是偏移量

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        body{
            padding: 0;
            margin: 0;
            width: 100vw;
            height: 100vh;
        }
        .container{
            position: absolute;
            left:10px;
            top:10px;
            width: 500px;
            height: 500px;
            background-color: #ffffff;
            box-sizing: border-box;
            border:1px solid #cccccc;

            overflow: hidden;
        }

        .child{
            width: 100%;
            height: 200%;
            background-color: red;
            border: 1px solid red;
            box-sizing: border-box;
        }

        .calcButton{
            position: absolute;
            left:0;
            bottom:0;
            width: 100px;
            height: 50px;
            box-sizing: border-box;
        }
        .child-wrapper{
            position: absolute;
            left:0;
            right: 0;
            top:0;
            bottom:50px;
            overflow-x: hidden;
            overflow-y: auto;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="child-wrapper">
            <div class="child"></div>
        </div>
        <button type="button" class="calcButton">计算</button>
    </div>
    <script>
        document.querySelector(".calcButton").addEventListener("click",function(){
            var childWrapperRect=document.querySelector(".child-wrapper") .getBoundingClientRect();
            var childRect=document.querySelector(".child") .getBoundingClientRect();
            this.innerText="当前偏移-"+(childWrapperRect.top-childRect.top);
        });
    </script>
</body>
</html>

拿segmentfault这个网页来说

document.body.offsetHeight
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题