找到第一个可滚动的父级 [英] Find first scrollable parent

查看:104
本文介绍了找到第一个可滚动的父级的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我遇到这种情况需要将元素滚动到视口中。问题是我不知道哪个元素是可滚动的。例如,在Portrait中,body是可滚动的,而在Landscape中它是另一个元素(并且有更多情况可以改变可滚动元素)

I have this situation in which I need to scroll an element into the viewport. The problem is that I don't know which element is scrollable. For example, in Portrait the body is scrollable and in Landscape its an other element (and there are more situation which change the scrollable element)

现在问题,给定一个元素需要滚动到视口中,找到第一个可滚动父级的最佳方法是什么?

Now the question, given an element which needs to be scrolled into the viewport, what is the best way to find its first scrollable parent ?

我已经设置了一个演示这里。使用此按钮,您可以在两种不同情况之间切换

I've setup a demo here. With the button you can toggle between two different situations

<div class="outer">
    <div class="inner">
        <div class="content"> 
            ...
            <span>Scroll me into view</span>
        </div>
    </div>
</div>

正文可滚动或 .outer

有任何建议吗?

推荐答案

只需检查滚动条是否可见,如果没有看向父母。

Just check if the scrollbar is visible, if not look to the parent.

function getScrollParent(node) {
  if (node == null) {
    return null;
  }

  if (node.scrollHeight > node.clientHeight) {
    return node;
  } else {
    return getScrollParent(node.parentNode);
  }
}

这篇关于找到第一个可滚动的父级的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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