【发布时间】:2018-11-16 02:23:19
【问题描述】:
我正在尝试创建一页网站。现在我试图在滚动到指定的section 时将活动类添加到我的a。例如,当我滚动到 #services 我的带有 url #service 的 href 将变成这样
<a class="active" href="#services"><img height="22px" width="22px" src="assets/icon/tools.png"> <span> Service </span></a>
这是我的html
<div class="sidenav">
<a href="#home"><img height="22px" width="22px" src="assets/icon/home.png"> <span> Home </span></a>
<a href="#services"><img height="22px" width="22px" src="assets/icon/tools.png"> <span> Service </span></a>
<a href="#portofolio"><img height="22px" width="22px" src="assets/icon/profiles.png"> <span> Portofolio </span></a>
<a href="#about"><img height="22px" width="22px" src="assets/icon/info.png"> <span> About Us </span></a>
<a href="#contact"> <img height="22px" width="22px" src="assets/icon/customer-service.png"> <span> Contact Us </span></a>
</div>
<div class="main">
<section id="home"> Main </section>
<section id="services"> Services </section>
<section id="portofolio"> Portofolio </section>
<section id="about"> About Us</section>
<section id="contact"> Contact Us </section>
</div>
这是我的 js
$(document).ready(function(){
var before;
$("a").on('click', function(event) {
if (this.hash !== "") {
event.preventDefault();
var hash = this.hash;
$('html, body').animate({
scrollTop: $(hash).offset().top
}, 800, function(){
window.location.hash = hash;
});
}
});
$("a").click(function(){
if(before){
before.removeClass("active");
}
$(this).addClass("active");
before = $(this);
});
});
我已经尝试过这种方式,但现在我遇到了多个问题
var sections = $('section')
, nav = $('.sidenav')
, nav_height = nav.outerHeight();
$(window).on('scroll', function () {
var cur_pos = $(this).scrollTop();
sections.each(function() {
var top = $(this).offset().top - nav_height,
bottom = top + $(this).outerHeight();
if (cur_pos >= top && cur_pos <= bottom) {
nav.find('a').removeClass('active');
sections.removeClass('active');
$(this).addClass('active');
nav.find('a[href="#'+$(this).attr('id')+'"]').addClass('active');
}
});
});
第一个问题,但是当我进入第一部分时,我的href 没有active class,第二个问题是当我在任何部分时,链接到下一部分的链接是active
【问题讨论】:
-
为什么
a标签有两个点击处理程序?你的代码有什么问题,请解释一下。 -
@GurtejSingh 用于第一个处理程序将进入部分,第二个是将
active类添加到我的 href 并删除active -
@GurtejSingh 请检查我的问题,我已经更新了