如何使用jquery检查可滚动ul内部的element(li)是否水平可见?

时间:2019-07-19 03:29:20

标签: javascript jquery html css

我曾尝试在StackOverflow中找到:“如何检查可水平滚动的div内的元素是否可见”,但我只发现了垂直滚动而不是水平滚动。

所以我在页面顶部有一个锚列表,向用户显示他们当前在哪个部分。

在滚动页面时,到达顶部<section></section>在0到30之间的distance > 0 && distance < 30将是活动元素,并且指向该div的各个锚点将具有“活动”类< / p>

当锚定为类active时,我需要检查水平滚动div中的锚是否可见或隐藏。如果看不见,则将父级<ul class="premium-vscroll-dots-list-custom">滚动到活动锚点的位置。

我现在的问题是,<ul class="premium-vscroll-dots-list-custom">仅滚动到前几个隐藏元素的元素,然后停止工作。

请参见下面的详细代码:

var lastScrollTop = 0;
$(window).scroll(function(event) {

    if (window.pageYOffset != lastScrollTop) {
        lastScrollTop = window.pageYOffset;

        $('body ul.premium-vscroll-dots-list-custom').each(function() {
            $(this).find('li.premium-vscroll-dot-item').each(function() {
                var menu_anchor = $(this).data('menuanchor');
                var distance = $('section#' + menu_anchor).offset().top - $(window).scrollTop();

                if (distance > 0 && distance < 30) {
                    console.log('current active section is: ' + menu_anchor);
                    $('ul.premium-vscroll-dots-list-custom li.premium-vscroll-dot-item').removeClass('custom-active');
                    $(this).addClass('custom-active');

                    var next_li_item = $(this).next();
                    var islastchild = $(this).is(":last-child");
                    var next_menu_anchor = next_li_item.data('menuanchor');

                    console.log('next li item is: ' + next_menu_anchor);
                    if ($(this).isInViewportHorizontally()) {
                        console.log('yes the anchor is in viewport');
                    } else {
                        console.log('the anchor is not in the viewport');
                        var position_of_parents_left = $(this).parent().offset().left;
                        var position_of_active_item = $(this).position().left;

                        $(this).parent().scrollLeft(position_of_active_item);
                    }
                }
            });
        });
        lastScrollTop++;
    }
});

用于检查锚点是否在水平视口内的功能:

$.fn.isInViewportHorizontally = function() {
    // let elementTop = $(this).offset().top;
    let elementLeft = $(this).offset().left;
    let elementRight = elementLeft + $(this).outerWidth();

    let viewportLeft = $(window).scrollLeft();
    let viewportRight = viewportLeft + $(window).width();

    return elementRight > viewportLeft && elementLeft < viewportRight;
};

enter image description here

enter image description here

0 个答案:

没有答案