我的页面下有一个锚点菜单。当您单击任何一个链接时,它会向下滚动到右侧部分,但如果您单击同一链接,则会更改其位置(减去57px)。如何在页面加载后从头开始获得正确的位置?
这是我的代码:
$(document).ready(function(){
var top = $('#anchor-menu').offset().top;
$(window).scroll(function(){
var y = $(this).scrollTop();
if (y >= top) {
$('#anchor-menu').addClass('fixed');
}
else {
$('#anchor-menu').removeClass('fixed');
}
});
$('#menu-anchor-menu li').each(function(){
var hash = $(this).find('a').attr('href');
var tag = hash.split('#');
$(this).find('a').click(function(e){
e.preventDefault();
var pos = $('#'+tag[1]).offset().top - $('#anchor-menu').height();
$('html, body').stop().animate({
scrollTop: pos
}, 1500, 'easeInOutExpo');
$('#menu-anchor-menu li a').removeClass('active');
$(this).addClass('active');
return false;
});
});
});
答案 0 :(得分:0)
所以发生的事情是:
修复是在发生点击事件时“检查”滚动事件中的逻辑,或者是阻止上述步骤发生的其他一些神奇方法。解决方案如下,我不知道它是否是最好的。
$(document)
.ready(documentReady);
function checkScroll() {
var $menu = $('#anchor-menu');
var top = $menu.offset().top,
y = $menu.scrollTop();
if (y >= top) {
$menu.addClass('fixed');
} else {
$menu.removeClass('fixed');
}
}
function documentReady() {
$(window)
.scroll(checkScroll);
$('#menu-anchor-menu li')
.each(forEachLi);
function forEachLi() {
checkScroll();
var hash = $(this).find('a').attr('href');
var tag = hash.split('#');
$(this).find('a').click(anchorClicked);
function anchorClicked(e) {
e.preventDefault();
var pos = $('#' + tag[1]).offset().top - $('#anchor-menu').height();
$('html, body').stop().animate({
scrollTop: pos
}, 1500, 'easeInOutExpo');
$('#menu-anchor-menu li a').removeClass('active');
$(this).addClass('active');
return false;
}
}
}