我想使用Jquery根据用户滚动的距离在我的锚链接上添加类.我能够添加类,但它不会被删除使用removeClass.我确定问题是我在jquery中使用的选择器.我是否需要遍历并从父元素添加特定选择器,而不是直接removeClass在我的锚链接上分配.
我不是将类添加到列表元素,而是将类应用于锚链接本身,这是我个人的选择.
HTML
<ul>
<li><a class="scroll" href="#first">About Me</a></li>
<li><a class="scroll" href="#second">Portfolio</a></li>
<li><a class="scroll" href="#third">Contact</a></li>
</ul>
<div class="home" style="height:1000px; background-color:red;"></div>
<div class="about-me" id="first" style="height:1000px; background-color:green;"></div>
<div class="portfolio" id="second" style="height:1000px; background-color:blue;"></div>
<div class="contact" id="third" style="height:1000px; background-color:orange;"></div>
Run Code Online (Sandbox Code Playgroud)
CSS
.active {
color:gray;
}
Run Code Online (Sandbox Code Playgroud)
JQUERY
$(document).ready(function(){
var scrollLink = $('.scroll');
scrollLink.click(function(event){
event.preventDefault();
$('body,html').animate({
scrollTop: $(this.hash).offset().top
}, 1000)
})
$(window).scroll(function(){
var scrollLoc = $(this).scrollTop();
scrollLink.each(function(){
var traverse = $(this.hash).offset().top - 20;
if (traverse <= scrollLoc){
$(this).addClass('active');
$(this).removeClass('active');
}
})
})
})
Run Code Online (Sandbox Code Playgroud)
我希望其他锚链接中的类在屏幕上不显示时会被删除.