Capture first visible div id while scrolling (view

2019-02-26 05:35发布

问题:

I have this page:

I want to capture on which div I am while I'm scrolling.

I know If I use:

if( $(document).scrollTop() > $('#div1').position().top) {  
console.log('Div1')
  }

...it will capture the div1 but instead of using this code for every div I want to set 1 snippet for all divs

Something like:

var a =   // The div i am at
if( $(document).scrollTop() > $(a).position().top) {    
    console.log($(a).attr('id'))
}

I am looking something like the viewport: http://www.appelsiini.net/projects/viewport/3x2.html

Can I achieve that without a plugin, simply 2-3 lines?

回答1:

Here's a nice way to do it. You may want to optimize the '<=' with a pixel offset to improve user experience and move the div selector ($divs) outside the callback to increase performance. Have a look at my fiddle: http://jsfiddle.net/brentmn/CmpEt/

$(window).scroll(function() {

    var winTop = $(this).scrollTop();
    var $divs = $('div');

    var top = $.grep($divs, function(item) {
        return $(item).position().top <= winTop;
    });
});


回答2:

Just throw it into a loop.

var list = [];
$("div").each(function(index) {
    if( $(document).scrollTop() > $(this).position().top) 
        list.push($(this));
});

alert(list);

The list will than have every div that is within your viewport.



回答3:

I'd suggest using the jQuery Inview plugin:

https://github.com/protonet/jquery.inview

Well maintained Plugin that detects whatever content is in the viewer currently, enabling you to bind functions to an inview event. So as soon as your div is in view you could fire off all the relevant functions you wanted and then again when it has left the users view. Would be great for your needs.



回答4:

   $(window).scroll(function () {

        $("#privacyContent div").each(function () {
            var bottomOffset = ($(this).offset().top + $(this).height());
            console.log("Botom=",bottomOffset ,"Win= ", $(window).scrollTop());
            if (bottomOffset > $(window).scrollTop()) {

                $("#menu a").removeClass("active");
              //  console.log("Div is= ",$(this).attr('id'));
                $("#menu a[href='#" + $(this).attr('id') + "']").addClass("active");
                $(".b").removeClass("fsActive");
                var div = $(this);
                div.find(".b").addClass("fsActive");

                return false;
            }
        });

});

I do it like this it works fine it detect all div id