元素在可滚动容器中是否可见

Is element visible in scrollable container

我正在尝试为 bootstrap 创建一个完全支持样式的选择字段。我快完成了,但我想让控件正确处理向上和向下箭头键。如果您使用箭头将所选项目移出菜单的可见部分,我希望它滚动到活动项目。

我能找到的大多数关于如何使这样的东西工作的例子只关心在浏览器视口中。我需要检查某个元素在设置了溢出的不同容器元素中是否可见。

我当前的尝试导致菜单在需要之前向下滚动,并且永远不会向上滚动以跟随活动项目。

我在站点中使用 jQuery,因此您可以在您的答案中使用它,或者直接使用 javascript。请不要引用任何额外的库,我想保持这个简单的解决方案。

$.fn.visible = function(partial, parent){
    var $w              = parent ? $(parent): $(window);
    var $t              = $(this),
        viewTop         = $w.scrollTop(),
        viewBottom      = viewTop + $w.height(),
        _top            = $t.offset().top,
        _bottom         = _top + $t.height(),
        compareTop      = partial === true ? _bottom : _top,
        compareBottom   = partial === true ? _top : _bottom;

    return ((compareBottom <= viewBottom) && (compareTop >= viewTop));
};

jsfiddle example

我找到了一种方法来判断子元素在可滚动父元素中是否可见。这是我想出的 jQuery 函数。

$.fn.visible = function(partial, parent, child){
    var $outer = $(parent);
    var $child = $(child);

    if(partial)
        return ($child.position().top >= 0 && $child.position().top < $outer.height());
    else
        return ($child.position().top - $child.height() >= 0 && $child.position().top + $child.height() < $outer.height());
};