簡體   English   中英

JavaScript滾動當前視圖的元素ID

[英]JavaScript Scroll current view's element id

如果已經提出/回答了這個問題,我們深表歉意。 我有一個帶有很多段落標簽的html頁面(此頁面具有JQuery庫)。 每個段落(p)標簽都與一個帶有名稱的錨標簽相關聯。 請注意,這些段落中的內容可能有所不同。 當用戶滾動頁面時,如何在當前視圖中獲取定位標記的名稱?

  

您可以使用

$(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
            }
        });
    });
});

演示

注意:別忘了包含Jquery

解釋: .each() $(this)選擇名稱以para .each() closest('p')開頭的錨點,以選擇此錨點的父<p>

如果有人對開箱即用的解決方案感興趣,也請參閱https://www.customd.com/articles/13/checking-if-an-element-is-visible-on-screen-using-jquery 將其與Mohamed-Yousef答案混合使用時效果很好。

  • 添加jQuery參考
  • 添加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