如何使用滚动位置检测屏幕中央的哪个元素? [英] How to detect which element is on the center of the screen with scroll position?
问题描述
我想检测在向下/向上滚动时在屏幕上可见的元素. 我必须在针对该元素的菜单上将其设置为活动菜单项.
I want to detect which element is visible on the screen when scrolling down/up. I have to set as active menu item on the menu which targets that element.
// must have a page class
$('.page').each(function(){
$positionData[$(this).attr('id')] = $(this).offset().top;
});
$(document).scroll(function(){
var $position = $(this).scrollTop();
if($position > $height && !$body.hasClass('scrolled')) {
$body.addClass('scrolled');
//detech the scroll is between an element offset
} else if($position < $height) {
$body.removeClass('scrolled');
}
});
有什么主意吗?
推荐答案
对于 Bootstrap 用户;
已经可以找到一个名为Scrollspy的组件.
There is a component already can be found named Scrollspy.
如何使用?
1:为身体添加相对位置.
1: Add relative positioning to body.
body {
position: relative;
}
2:将data-spy ="scroll"和data-target ="属性添加到您的身体. (数据目标必须以您的菜单为目标)
2: Add data-spy="scroll" and data-target="" attributes to your body. (data-target must target your menu)
<body data-spy="scroll" data-target="#navbar-example">
3:设置菜单.请勿将Nav类添加到您的ul/ol元素中.
3: Set your menu. Don't for get to add nav class to your ul/ol element.
<div id="navbar-example">
<ul class="nav">
<li><a href="#home">HOME</a></li>
<li><a href="#project">PROJECT</a></li>
</ul>
</div>
4:检查目标元素,每个元素必须具有与链接目标相同的id属性.
4: Check your target elements to every element must have an id attribute same as your link targets.
<div id="home"></div>
这篇关于如何使用滚动位置检测屏幕中央的哪个元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!