How to detect which element is on the center of th

2019-06-14 10:17发布

问题:

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>