获取div的非溢出部分的高度 [英] Get height of non-overflowed portion of div

查看:154
本文介绍了获取div的非溢出部分的高度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个包装器div,其上有一个溢出:隐藏,并且内部的div跨越可见部分。如何获得内部div的可见高度?

Say I have a wrapper div with a overflow:hidden on it and a div inside that that spans far below the visible portion. How can I get the visible height of the internal div?

<div id="wrapper" style="overflow: hidden; height:400px;">
    <div id="inner">
        <!--Lots of content in here-->
    </div>
<div>

我尝试获取内部div的高度的每个方法都返回包括隐藏部分在内的完整高度,即2000px。我希望能够得到只有可见部分的高度,所以在这个例子中是400px。

Every method I try attempting to get the height of the inner div returns the complete height including the hidden parts, i.e. 2000px. I want to be able to get the height of only the visible portion, so 400px in this example case.

我知道我可以得到<$ c的高度$ c> parentNode ,但在生产中,内部div可能不是第一个孩子。因此可能有其他div将它们分开,因此 #inner 的高度将为400 - 无论它与 #wrapper之间的元素偏移如何

I know I could just get the height of the parentNode, but in production, the inner div might not be a first child. So there might be other divs separating them, and so the height of #inner would be 400 - whatever the offsets of the elements between it and #wrapper.

推荐答案

作为基本算法,这可行:

As basic algorithm this could work:

var offset = 0;
var node = document.getElementById("inner");
while (node.offsetParent && node.offsetParent.id != "wrapper")
{
    offset += node.offsetTop;
    node = node.offsetParent;
}
var visible = node.offsetHeight - offset;

但是如果你正在做这些事情,也许你已经使用了jQuery,这可能是服务的 .height() .offset()函数:

But if you're doing these kinds of things, maybe you already use jQuery, which might be of service with its .height() and .offset() functions:

$("#wrapper").height()-
$("#inner").offset()['top']+
$("#wrapper").offset()['top'];  

这篇关于获取div的非溢出部分的高度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆