【发布时间】:2019-01-11 19:31:56
【问题描述】:
我想使用 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>
CSS
.active {
color:gray;
}
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');
}
})
})
})
我希望其他锚链接中的类在屏幕上未显示时会被删除。
【问题讨论】:
-
我会亲自从所有元素中删除该类,然后将其添加到相关的元素中,但下面的@KevinKoobs 提供了一个干净的替代方案。