[英]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答案混合使用时效果很好。
$(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.