当我滚动到我的网页的某个部分时,该特定的导航丸部分将亮起,如图所示:
当我滚动到Home和Resume时,它的工作方式与预期的一样。但是,当我点击时,让我们说“恢复”,然后滚动 - 观察当我向下滚动到联系人时会发生什么:
现在突出显示Resume和Contact。当我把这段代码拿走时,它按预期工作。第一部分是平滑过渡滚动(点击时),第二部分是滚动,都是用jQuery编写的。
//Smooth transition scroll when nav pill is clicked
//When I take this code out, it works fine
var anchor = $('html, body');
$('a').click(function(){
$(anchor).animate({
scrollTop: $($(this).attr('href')).offset().top
}, 500);
return false;
});
//Change active class when scrolling
$(window).scroll(function() {
var position = $(document).scrollTop();
if (position <= home.top) {
$('.home-class').removeClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').removeClass('active');
}
if (position >= home.top) {
$('.home-class').addClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').removeClass('active');
}
if (position > resume.top) {
$('.home-class').removeClass('active');
$('.resume-class').addClass('active');
$('.contact-class').removeClass('active');
}
if (position > contact.top) {
$('.home-class').removeClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').addClass('active');
}
});
如果有人可以指出发生了什么,我将不胜感激。
答案 0 :(得分:0)
存在逻辑问题。您应首先将位置与较大的顶部位置进行比较。
例如,如果resume.top为500,则contact.top为700,position为750 ..
$(window).scroll(function() {
var position = $(document).scrollTop();
if (position <= home.top) {
$('.home-class').removeClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').removeClass('active');
}
if (position >= home.top) {
$('.home-class').addClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').removeClass('active');
}
/* .resume-class will have active class because 701 > 500 */
if (position > resume.top) {
$('.home-class').removeClass('active');
$('.resume-class').addClass('active');
$('.contact-class').removeClass('active');
}
/* .contact-class will have active class too because 701 > 700 */
if (position > contact.top) {
$('.home-class').removeClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').addClass('active');
}
});
所以你需要像这样改变你的代码
$(window).scroll(function() {
var position = $(document).scrollTop();
if (position >= contact.top) {
$('.home-class').removeClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').addClass('active');
return;
}
if (position >= resume.top) {
$('.home-class').removeClass('active');
$('.resume-class').addClass('active');
$('.contact-class').removeClass('active');
return;
}
if (position >= home.top) {
$('.home-class').addClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').removeClass('active');
return;
}
if (position < home.top) {
$('.home-class').removeClass('active');
$('.resume-class').removeClass('active');
$('.contact-class').removeClass('active');
}
});