找到第一个可滚动的父级
我遇到这种情况需要将元素滚动到视口中。问题是我不知道哪个元素是可滚动的。例如,在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);
}
}