简体   繁体   中英

Get Current Sections ID

I was trying to get ID of current section. Here is the code snippet what I tried:

$(document).on('scroll', function() {
    alert($(this).$("section").attr('id'));
}

But found no result. How can I get the id of a section while scrolling?

First of all, you are not detecting a current section in your code (by "current" I mean the section currently showing on the screen). To detect this section you should find current scroll position and compare it to section position.

    $(document).scroll(function () {
        $('section').each(function () {
            if($(this).position().top <= $(document).scrollTop() && ($(this).position().top + $(this).outerHeight()) > $(document).scrollTop()) {
                console.log($(this).attr('id'));
            }
        });
    });

If this plugin works the way it should, then you could do this in the scroll event:

$('section').each(function() {
  if($(this).visible())
    console.log($(this).attr('id'));
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM