Key*_*See 5 html javascript css jquery
我想实现某种平滑的滚动,所以我制作了这个脚本:
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).offset().top
}, 500);
return false;
});
Run Code Online (Sandbox Code Playgroud)
问题?当我点击'a'时,offset.top()值会改变另一个奇怪的值并在它们之间切换?为什么会发生这种情况,我该如何解决?
http://jsfiddle.net/StartStep/9SDLw/2947/
我认为问题在于以scroll.top()另一种方式获得价值... jsfiddle.net/9SDLw/2950/
$('a').click(function(){
var sclink = $(this).attr('href');
$('.menu').animate({
scrollTop: $(sclink).position().top
}, 500);
logit('Anchor: '+sclink+'; Offset top value: <b>'+$(sclink).offset().top+'</b>')
return false;
});
Run Code Online (Sandbox Code Playgroud)
用position而不是offset.
原因是offset相对于视口,因为它看起来你滚动太远了,但这是因为视口区域的顶部被你的布局遮挡了,所以offset实际上并不是你想要的,而是position.
您还应该stop在调用之前添加引用,animate以确保用户快速连续点击行为是否符合预期(动画队列基本上是刷新的)
考虑到这一点,你的HTML也需要一些工作 - 例如,可点击链接没有关闭标签.
将滚动代码更改为:
$('.menu').stop(true,true).animate({
scrollTop: $(sclink).position().top
}, 500);
Run Code Online (Sandbox Code Playgroud)