【发布时间】:2014-04-03 08:03:02
【问题描述】:
我正在做一个页面,其中导航 .active 类应该在滚动和点击时都发生变化。向下滚动时,我也在更改标题类(“.large”和“.small”),但这两个脚本不知何故不能相互配合。
为了调整标题大小,我正在这样做:
$(document).on("scroll",function(){
if($(document).scrollTop()>200){
$('header').removeClass('large').addClass('small');
} else{
$('header').removeClass('small').addClass('large');
}
});
为了更改活动课程,我正在这样做:
$(document).ready(function () {
$(document).on("scroll", onScroll);
//smoothscroll
$('a[href^="#"]').on('click', function (e) {
e.preventDefault();
$(document).off("scroll");
$('a').each(function () {
$(this).removeClass('active');
})
$(this).addClass('active');
var target = this.hash,
menu = target;
$target = $(target);
$('html, body').stop().animate({
'scrollTop': $target.offset().top+2
}, 500, 'swing', function () {
window.location.hash = target;
$(document).on("scroll", onScroll);
});
});
});
function onScroll(event){
var scrollPos = $(document).scrollTop();
$('#top-menu a').each(function () {
var currLink = $(this);
var refElement = $(currLink.attr("href"));
if (refElement.position().top <= scrollPos && refElement.
position().top + refElement.height() > scrollPos) {
$('#top-menu ul li a').removeClass("active");
currLink.addClass("active");
}
else{
currLink.removeClass("active");
}
});
}
这在滚动时非常有效,但是单击顶部导航链接只会使“标题”功能崩溃,并且不再调整大小。谁能看出问题出在哪里?
【问题讨论】:
-
尝试对文档元素触发 crollTop 动画而不是
'html, body' -
不幸的是,这没有帮助
标签: javascript jquery navigation