【发布时间】:2015-11-05 19:34:24
【问题描述】:
我有一个 C# MVC Web 应用程序,它显示了在数字标牌上显示的滚动时间表。它使用 JQuery animate 函数在到达底部时向上滚动回顶部(在运行时不断循环)。我将逐步解释应用程序的运行。
当应用程序启动时,它会像往常一样滚动到底部,然后以动画方式回到顶部,但是在某些设置下,在第二遍以及每次滚动出初始视图后它都会卡住一点.然后应用程序将滚动回顶部,然后正常向下滚动到底部。这就是反弹。当动画功能设置为较慢(使用“慢”或更高的值,如 3000)时,似乎会发生此问题。
这是控制滚动到底部和动画回到顶部的代码:
$(document).ready(function () {
var div = $('#docket');
var scrollDown = setInterval(function () {
var pos = div.scrollTop();
div.scrollTop(pos + 2);
}, 75)
// Check if we are at the bottom. If so, wait 1 second and scroll to the top.
div.bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() >= this.scrollHeight) {
div.delay(1000).animate({ scrollTop: 0 }, 'slow');
}
})
});
编辑 1 由于问题仍在发生,我已经进行了一些额外的调查。我认为这可能与 delay() 和 setInterval() 的时间有关,但到目前为止,事实证明这个问题很难处理。我添加了一些警报,以便我可以轻松判断脚本何时开始滚动到顶部。令我惊讶的是,我注意到反弹发生时它们没有被触发,只是在初始(和正确)滚动到顶部时触发。我对 JQuery 不是很熟悉,所以我有点想把东西扔在墙上,看看它们现在是否会粘住。
编辑 2 使用此答案Callback of .animate() gets called twice jquery 中的部分代码。我发现我的#docket div 被动画了两次。该答案中的修复并不能阻止反弹的发生。这是来自链接答案的代码的最新版本。完成动画案卷警报显示两次。
$(document).ready(function () {
var div = $('#docket');
var scrollDown = setInterval(function () {
var pos = div.scrollTop();
div.scrollTop(pos + 2);
}, 50)
// Check if we are at the bottom. If so, wait 1 second and scroll to the top.
div.bind('scroll', function () {
if ($(this).scrollTop() + $(this).innerHeight() == this.scrollHeight) {
div.delay(100).animate({ scrollTop: 0 }, 'slow', function() {
// Called per element
alert("Done animating " + this.id);
}).promise().then(function() {
// Called when the animation in total is complete
alert("Completed animation");
});
}
})
});
【问题讨论】:
标签: jquery