javascript 如何禁用滚动直到动画完成?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11649456/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-26 13:54:30  来源:igfitidea点击:

How to disable scrolling until animation is complete?

javascriptjqueryscrolljquery-animate

提问by Sven

I am using this code to scroll to a certain element on my page:

我正在使用此代码滚动到我页面上的某个元素:

$("html, body").animate({scrollTop: $(".myDiv").offset().top}, 300);

It works, but there is one issue with it: When the user scrolls down while the script scrolls up, there is some juddering because there are two scroll commands at the same time in different directions - sounds logical to me.

它有效,但有一个问题:当用户向下滚动而脚本向上滚动时,会出现一些颤抖,因为在不同方向同时有两个滚动命令 - 对我来说听起来很合乎逻辑。

I checked some other sites with such scroll functionality, there is no juddering. So what's the trick to prevent this?

我检查了其他一些具有这种滚动功能的网站,没有颤抖。那么有什么技巧可以防止这种情况呢?

采纳答案by Barlas Apaydin

Thats a jQuery bug when you use animate with scrolling, good detection.

当您使用带有滚动的动画时,这是一个 jQuery 错误,良好的检测。

I did a research how to turn it off scrolling and find this question : How to disable scrolling temporarily?

我做了一项研究如何关闭滚动并找到这个问题:如何暂时禁用滚动?

Here is jsFiddle. You will see after click; user cant scroll untill animate complete.

这是jsFiddle。点击后你会看到;用户无法滚动,直到动画完成。

$('.myDiv').click(function(){

    disable_scroll();

    $('html, body').stop().animate({ scrollTop: 0 }, 700,function() {
        enable_scroll();
    });
});

edit: thanks to galambalazs btw.

编辑:感谢 galambalazs 顺便说一句。

回答by Avi Pinto

an idea - try hooking to the scroll event and use http://api.jquery.com/stop/to stop your animation .. bad idea..

一个想法 - 尝试挂钩滚动事件并使用http://api.jquery.com/stop/来停止你的动画..坏主意..

same problem with a solution - let user scrolling stop jquery animation of scrolltop?

解决方案的相同问题 -让用户滚动停止滚动顶部的 jquery 动画?