如何通过滚动位置检测哪个元素位于屏幕中心?

How to detect which element is on the center of the screen with scroll position?

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

// 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 插件 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 用户;

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

Scrollspy

如何使用?

1:给body添加相对定位。

body {
    position: relative;
}

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

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

3:设置菜单。不要将导航 class 添加到您的 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: 检查你的目标元素,每个元素都必须有一个与你的 link 目标相同的 id 属性。

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