Get height of non-overflowed portion of div

后端 未结 5 1748
[愿得一人]
[愿得一人] 2020-12-16 01:34

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 in

5条回答
  •  天涯浪人
    2020-12-16 02:29

    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:

    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.

    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.visibility property of the node and all its ancestors.

提交回复
热议问题