javascript 获取 div 未溢出部分的高度

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12868287/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 17:17:59  来源:igfitidea点击:

Get height of non-overflowed portion of div

javascriptheightoverflowoffset

提问by ryandlf

Say I have a wrapper div with a overflow:hiddenon 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,上面有一个overflow:hidden,里面有一个 div,它远远低于可见部分。如何获得内部div的可见高度?

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

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.

我尝试获取内部 div 高度的每种方法都会返回包括隐藏部分在内的完整高度,即 2000 像素。我希望能够仅获得可见部分的高度,因此在此示例中为 400px。

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 #innerwould be 400 - whatever the offsets of the elements between it and #wrapper.

我知道我只能获得 的高度parentNode,但在生产中,内部 div 可能不是第一个孩子。因此,可能有其他 div 将它们分开,因此 的高度#inner将为 400 - 无论它与#wrapper.

采纳答案by Wolfgang Stengel

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;

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:

但是,如果您正在做这些事情,也许您已经使用了 jQuery,它的功能.height().offset()功能可能会有所帮助:

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

回答by Paul S.

Quick algorithm that goes up the DOM tree looking at window.getComputedStylefor overflow: hidden

快速算法上升DOM树看window.getComputedStyleoverflow: hidden

function visibleArea(node){
    var o = {height: node.offsetHeight, width: node.offsetWidth}, // size
        d = {y: (node.offsetTop || 0), x: (node.offsetLeft || 0), node: node.offsetParent}, // position
        css, y, x;
    while( null !== (node = node.parentNode) ){  // loop up through DOM
        css = window.getComputedStyle(node);
        if( css && css.overflow === 'hidden' ){  // if has style && overflow
            y = node.offsetHeight - d.y;         // calculate visible y
            x = node.offsetWidth - d.x;          // and x
            if( node !== d.node ){
                y = y + (node.offsetTop || 0);   // using || 0 in case it doesn't have an offsetParent
                x = x + (node.offsetLeft || 0);
            }
            if( y < o.height ) {
                if( y < 0 ) o.height = 0;
                else o.height = y;
            }
            if( x < o.width ) {
                if( x < 0 ) o.width = 0;
                else o.width = x;
            }
            return o;                            // return (modify if you want to loop up again)
        }
        if( node === d.node ){                   // update offsets
            d.y = d.y + (node.offsetTop || 0);
            d.x = d.x + (node.offsetLeft || 0);
            d.node = node.offsetParent;
        }
    }
    return o;                                    // return if no hidden
}

example fiddle(look at your console).

示例小提琴(看看你的控制台)。

回答by Zach Saucier

The only way I've found to do this in every circumstance, including when there's overflow, transform: translate()s are used, and there are other nested containers in between an element and the element that's hiding its overflow is to combine .getBoundingClientRect()with a reference to the ancestor that's hiding the element's overflow:

我发现在每种情况下都可以这样做的唯一方法,包括当有溢出时,使用transform: translate()s,并且在元素和隐藏其溢出的元素之间还有其他嵌套容器是结合.getBoundingClientRect()对祖先的引用隐藏元素的溢出:

function getVisibleDimensions(node, referenceNode) {
    referenceNode = referenceNode || node.parentNode;

    var pos = node.getBoundingClientRect();
    var referencePos = referenceNode.getBoundingClientRect();

    return {
        "width": Math.min(
            node.clientWidth,
            referencePos.left + referenceNode.clientWidth - pos.left, 
            node.clientWidth - (referencePos.left - pos.left)
        ),
        "height": Math.min(
            node.clientHeight, 
            referencePos.top + referenceNode.clientHeight - pos.top,
            node.clientHeight - (referencePos.top - pos.top)
        )
    }
}

Demo.

演示

If a reference node is not given, the parent node is assumed: Demo.

如果未给出参考节点,则假定父节点为:Demo

Note that this doesn't take into account whether or not an element is viewable in the viewport, just visible (not hidden due to overflow). If you need both, you can combine functionality with this answer. It also has no check of visibility: hidden, so if you need that you need to check the style.visibilityproperty of the node and all its ancestors.

请注意,这并没有考虑元素是否在 viewport 中可见,只是可见(由于溢出而不是隐藏)。如果您需要两者,您可以将功能与此答案结合使用。它也没有检查visibility: hidden,因此如果您需要检查style.visibility节点及其所有祖先的属性。

回答by akostajti

The code below computes the visible portion of an element. By visible portion I mean the part that is visible in the window, but I think you can easily alter it to base the computation on an arbitrary container element.

下面的代码计算元素的可见部分。可见部分是指在window 中可见的部分,但我认为您可以轻松更改它以基于任意容器元素进行计算。

function computeVisibleHeight ($t) {
        var top = $t.position().top;
        var windowHeight = $(window).height();
        var scrollTop = $(window).scrollTop();
        var height = $t.height();

        if (top < scrollTop && height - scrollTop >= windowHeight) {
            // first case: the top and the bottom of the element is outside of the window
            return windowHeight;
        } else if (top < scrollTop) {
            // second: the top is outside of the viewport but the bottom is visible
            return height - (scrollTop - top);
        } else if (top > scrollTop && top + height < windowHeight) {
            // the whole element is visible
            return height;
        } else {
            // the top is visible but the bottom is outside of the viewport
            return windowHeight - (top - scrollTop);
        }
    }

The code is using jquery.

代码使用 jquery。

回答by Amareswar

I think keeping a sibling next to it, calculating its scrollTop and the overflow element scrollTop and then subtracting it from the siblings scroolTop might work

我认为在它旁边保持一个兄弟姐妹,计算它的 scrollTop 和溢出元素 scrollTop 然后从兄弟姐妹 scoolTop 中减去它可能会起作用