使用 jQueryscrollTop 时消除抖动
我有一个功能,当按下键盘上的向下箭头时,可以向下滚动到文章的下一部分;当按下向上箭头时,可以向上滚动。它工作正常,但是在滚动之前有轻微的“弹跳”或“抖动”。
我能够通过让函数返回 false 来部分修复这个问题,但是,返回 false 会吞掉按键事件,使我无法使用键盘与浏览器交互。
关于如何消除“抖动”同时释放键盘的任何想法?
var $sections = $('.section');
var curr = -1;
$(document).keydown(function(e){
prev = (curr < 0)? $sections.length-1: curr-1;
next = (curr >= $sections.length-1)? -1: curr+1 ;
switch (e.keyCode) {
case 38: // up key
s = $sections.eq(prev).offset().top;
curr = prev;
break;
case 40: // down key
s = $sections.eq(next).offset().top;
curr = next;
break;
default:
break;
}
if (curr == -1 ){
$('html, body').animate({scrollTop: 0}, 'slow');
}
else{
$('html, body').animate({scrollTop: s}, 'slow');
}
return e;
});
I've got a function that scrolls down to the next section of an article when the down arrow on the keyboard is pressed and scrolls up when the up arrow is pressed. Its working fine, however there is a slight "bounce" or "jitter" just before it scrolls.
I was able to partial fix for this problem by having the function return false, however, returning false swallows the key down event, leaving me unable use my keyboard to interact with the browser.
Any ideas on how to eliminate the "jitter" while at the same time freeing up my keyboard?
var $sections = $('.section');
var curr = -1;
$(document).keydown(function(e){
prev = (curr < 0)? $sections.length-1: curr-1;
next = (curr >= $sections.length-1)? -1: curr+1 ;
switch (e.keyCode) {
case 38: // up key
s = $sections.eq(prev).offset().top;
curr = prev;
break;
case 40: // down key
s = $sections.eq(next).offset().top;
curr = next;
break;
default:
break;
}
if (curr == -1 ){
$('html, body').animate({scrollTop: 0}, 'slow');
}
else{
$('html, body').animate({scrollTop: s}, 'slow');
}
return e;
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
想必您可以简单地添加一个简单的
if
语句,该语句仅在keyCode
向上和向下匹配时才执行滚动代码:下面是一个简单的演示:http://jsfiddle.net/yijian/SceDY/1/
查看代码,您可能还应该使用
var
关键字来限制变量prev
、next
和s
的范围。如果按下向上和向下以外的任何其他按钮,当前代码的行为会不稳定。Presumably you can simply add a simple
if
statement that will only execute the scrolling code if thekeyCode
matches up and down:Here's a simple demonstration of this in effect: http://jsfiddle.net/yijiang/SceDY/1/
Looking through the code, you should probably also use the
var
keyword to limit the scope of your variablesprev
,next
ands
. The current code behaves erratically if anything else other than up and down is pressed.谢谢 Yi...作为替代方案...我只是通过将默认 switch case 设置为返回 e 来使其工作。那么函数底部的return返回的是false。
结果看起来像这样:
Thanks Yi...as an alternative...I just got it to work by setting the default switch case to return e. Then the return at the bottom of the function returns false.
The result looks something like this: