简体   繁体   English

JavaScript滚动当前视图的元素ID

[英]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. 我有一个带有很多段落标签的html页面(此页面具有JQuery库)。 Each paragraph (p) tag is associated with an anchor tag with a name. 每个段落(p)标签都与一个带有名称的锚标签相关联。 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 注意:别忘了包含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 解释: .each() $(this)选择名称以para .each() closest('p')开头的锚点,以选择此锚点的父<p>

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. 如果有人对开箱即用的解决方案感兴趣,也请参阅https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery Works well when you mix it with the Mohamed-Yousef answer. 将其与Mohamed-Yousef答案混合使用时效果很好。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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