Capture first visible div id while scrolling (view

2019-02-26 05:24发布

I have this page:

enter image description here

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?

4条回答
一夜七次
2楼-- · 2019-02-26 06:03

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;
    });
});
查看更多
迷人小祖宗
3楼-- · 2019-02-26 06:05

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.

查看更多
神经病院院长
4楼-- · 2019-02-26 06:10

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.

查看更多
成全新的幸福
5楼-- · 2019-02-26 06:13
   $(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

查看更多
登录 后发表回答