【问题标题】:How to detect which element is on the center of the screen with scroll position?如何通过滚动位置检测哪个元素位于屏幕中心?
【发布时间】:2015-06-11 08:08:01
【问题描述】:

我想检测向下/向上滚动时屏幕上可见的元素。 我必须在针对该元素的菜单上设置为活动菜单项。

// must have a page class
$('.page').each(function(){
    $positionData[$(this).attr('id')] = $(this).offset().top;
});

$(document).scroll(function(){
    var $position = $(this).scrollTop();
    if($position > $height && !$body.hasClass('scrolled')) {
        $body.addClass('scrolled');

        //detech the scroll is between an element offset
    } else if($position < $height) {
        $body.removeClass('scrolled');
    }
});

有什么想法吗?

【问题讨论】:

    标签: jquery html scroll position offset


    【解决方案1】:

    您可以使用 jquery 插件 inview (github) 来做到这一点。

    $('.scrollWatch').bind('inview', function (event, visible) {
        if (visible) {
            // do something here
            $(this).addClass('scrolled');
            $(this).text('mom! I\'m here.');
        } else {
            // do something here with invisible
            $(this).removeClass('scrolled');
            $(this).text('1');
        }
    });
    

    我为你创建了一个演示jsfiddle,请使用 DevTools 看看 HTML 有什么变化。

    【讨论】:

    • 谢谢。我找到了一个接近你的答案的解决方案。 bootstrap 已经有一个组件。滚动间谍。
    • 你能发布你的解决方案吗?
    【解决方案2】:

    对于Bootstrap 用户;

    已经可以找到一个名为 Scrollspy 的组件。

    Scrollspy

    如何使用?

    1:给body添加相对定位。

    body {
        position: relative;
    }
    

    2:将 data-spy="scroll" 和 data-target="" 属性添加到您的正文中。 (数据目标必须针对您的菜单)

    <body data-spy="scroll" data-target="#navbar-example">
    

    3:设置菜单。不要将导航类添加到您的 ul/ol 元素中。

    <div id="navbar-example">
        <ul class="nav">
            <li><a href="#home">HOME</a></li>
            <li><a href="#project">PROJECT</a></li>
        </ul>
    </div>
    

    4:检查你的目标元素,每个元素都必须有一个与你的链接目标相同的 id 属性。

    <div id="home"></div>
    

    【讨论】:

    • 这并不能解决问题,它会创建滚动到屏幕中心元素的能力。 OP想要一个事件说嘿我现在在屏幕中间..做点什么..该事件必须存在(使用scrollspy),因为当您滚动菜单时更新为scrollspy ..但我找不到任何文档它..
    猜你喜欢
    • 1970-01-01
    • 2019-04-26
    • 2012-01-27
    • 1970-01-01
    • 1970-01-01
    • 2012-04-09
    • 2020-01-08
    • 2016-02-07
    • 1970-01-01
    相关资源
    最近更新 更多