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

拥有回忆 提交于 2019-12-23 04:53:48

问题


I want to detect which element is visible on the screen when scrolling down/up. I have to set as active menu item on the menu which targets that element.

// 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');
    }
});

Any idea?


回答1:


You can use jquery plugin inview (github) to do that.

$('.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');
    }
});

I created a demo jsfiddle for you, please use DevTools to see what changes in HTML.




回答2:


For Bootstrap users;

There is a component already can be found named Scrollspy.

Scrollspy

How to use?

1: Add relative positioning to body.

body {
    position: relative;
}

2: Add data-spy="scroll" and data-target="" attributes to your body. (data-target must target your menu)

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

3: Set your menu. Don't for get to add nav class to your ul/ol element.

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

4: Check your target elements to every element must have an id attribute same as your link targets.

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


来源:https://stackoverflow.com/questions/30775096/how-to-detect-which-element-is-on-the-center-of-the-screen-with-scroll-position

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!