JavaScript滚动当前视图的元素ID [英] JavaScript Scroll current view's element id
问题描述
很抱歉,如果已经提出/回答了此问题.我有一个带有很多段落标签的html页面(此页面具有JQuery库).每个段落(p)标签都与一个带有名称的锚标签相关联.请注意,这些段落中的内容可能有所不同.当用户滚动浏览页面时,如何在当前视图中获取定位标记的名称?
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>
推荐答案
您可以使用
$(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
Note: don't forget to include Jquery
要说明:.each()
内的$(this)
选择名称以para ..开头的锚点.closest('p')
选择此锚点的父级<p>
.因此,在此范围内玩耍以达到您想要的东西
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
这篇关于JavaScript滚动当前视图的元素ID的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!