Javascript 当网站向下滚动时,Scrolltop功能会使网站抖动
我在我的网站上遇到了一个问题。我在javascript中使用了以下行Javascript 当网站向下滚动时,Scrolltop功能会使网站抖动,javascript,jquery,html,css,Javascript,Jquery,Html,Css,我在我的网站上遇到了一个问题。我在javascript中使用了以下行 $('html, body').animate({scrollTop: $(".single-post-content").offset().top}, 1000); 这是我的javascript函数 $(document).keydown(function(e){ if (e.keyCode === 39) { var $next, $selected = $(".current");
$('html, body').animate({scrollTop: $(".single-post-content").offset().top}, 1000);
这是我的javascript函数
$(document).keydown(function(e){
if (e.keyCode === 39) {
var $next, $selected = $(".current");
$next = $selected.next('li').length ? $selected.next('li') : $first;
$selected.removeClass("current");
$next.addClass("current");
$('html, body').animate({scrollTop: $(".single-post-content").offset().top}, 1000);
showPage(parseInt($next.text()))
}
});
$(document).keydown(function(e){
if (e.keyCode === 37) {
var $prev, $selected = $(".current");
$prev = $selected.prev('li').length ? $selected.prev('li') : $last;
$selected.removeClass("current");
$prev.addClass("current");
$('html, body').animate({scrollTop: $(".single-post-content").offset().top}, 1000);
showPage(parseInt($prev.text()))
}
});
所以,当我按下左箭头或右箭头时,它会设置动画并向上滚动到指定的div
。但当我尝试向下滚动时,windows会抖动,不让我向下滚动。我无法解决这个问题,也无法使它变得更顺利
更新
这是我的听起来你想要一个简单的捕捉,可以在用户交互时取消动画。像这样的方法应该会奏效:
$(document).on("scroll mousedown DOMMouseScroll mousewheel keydown", function (e) {
if (e.which > 0 || e.type === "mousedown" || e.type === "mousewheel") {
$('html, body').stop();
}
});
这是根据相关问题修改的:我认为您可以使用此代码创建
$('html, body').animate({scrollTop: $(".single-post-content").height()}, 800);
而不是
$('html,body').animate({scrollTop:$(“.single post content”).offset().top},1000);在此处输入代码
请在使用JS中使用的类的地方包含一个HTML示例。(例如,单帖内容)@Ramy我已经更新了我的问题。顺便说一句,不是我否决了这个问题。我尝试添加了你的代码。我认为它不起作用。我还更新了我的问题我更新了我的代码示例,以便在正确的选择器上运行stop
。我在你的网站上进行了测试,它似乎可以工作。是的,问题是当你试图滚动时,滚动动画仍然处于活动状态,这会强制产生一定的偏移。如果在按下方向键和滚动之间等待几秒钟,一切都会正常工作。使用stop()
似乎是正确的方法。或者将动画时间缩短为400
而不是1000
,我认为它在chrome上仍然有点摇晃。在Safari和Firefox上运行良好。