简体   繁体   中英

JavaScript Scroll current view's element id

Apologies if this question is already asked/answered. I have an html page (this page has JQuery library) with lots of paragraph tags. Each paragraph (p) tag is associated with an anchor tag with a name. Please note content inside these paragraphs may vary. When user scrolls through the page, how can I get the name of the anchor tag in the current view?

 <p><a name="para1"></a> some long text </p> <p><a name="para2"></a> some text </p> <p><a name="para3"></a> some long text </p> 

you can use

$(document).ready(function(){
    $(window).on('scroll',function(){
        var Wscroll = $(this).scrollTop();
        $('a[name^="para"]').each(function(){
            var ThisOffset = $(this).closest('p').offset();
            if(Wscroll > ThisOffset.top &&  Wscroll < ThisOffset.top  + $(this).closest('p').outerHeight(true)){
                $(this).closest('p').css('background','red');
                console.log($(this).attr('id')); // will return undefined if this anchor not has an Id
                // to get parent <p> id
                console.log($(this).closest('p').attr('id')); // will return the parent <p> id
            }
        });
    });
});

Demo

Note: don't forget to include Jquery

To Explain : $(this) inside .each() select anchors with name starts with para .. closest('p') to select parent <p> of this anchor .. so play around this to reach the thing you want

If anybody interest of a out the box solution, take a look at https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery as well. Works well when you mix it with the Mohamed-Yousef answer.

  • Add jquery reference
  • Add jquery.visible.js reference
 $(function(){ $(window).on('scroll',function(){ $('a[name^="para"]').each(function(){ var visible = $(this).visible( false ); if(visible){ console.log($(this).attr('name')); return false; } }); }); }); 

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