我正在尝试在我的网站上实现滚动到顶部动画 http://www.cmclove.org/bootstrap
但是每当我滚动到顶部并尝试向下滚动时,页面似乎在与我作斗争并且不想向下滚动。
您可能需要执行几次,或者尝试在动画完成后立即向下滚动
这是jquery:
$(document).ready(function() {
$(function() {
/* set variables locally for increased performance */
var scroll_timer;
var displayed = false;
var $message = $('#message a');
var $window = $(window);
var top = $(document.body).children(0).position().top;
/* react to scroll event on window */
$window.scroll(function(e) {
window.clearTimeout(scroll_timer);
e.preventDefault();
scroll_timer = window.setTimeout(function(e) {
if ($window.scrollTop() <= top) {
displayed = false;
$message.fadeOut(800);
e.preventDefault();
}
else if (displayed == false) {
displayed = true;
$message.stop(true, true).show(1000).click(function(e) {
$('html, body').animate({
scrollTop: 0
}, 'slow');
$message.fadeOut(1000);
e.preventDefault();
});
}
}, 100);
});
});
});
这是 html
<a id="top"></a>
<!--- all my html stuff -->
<div id="message"><a href="#top"></a></div>
</footer>
最佳答案
我知道发生了什么。每次发生“滚动到顶部”时,您都会绑定(bind)一个新的“点击”事件。由于它们相加,每次滚动条都会多卡住 1 秒。因此,当您第一次滚动到顶部时,不会有任何卡住。下次卡住一秒,下次卡住 2 秒,依此类推。
我认为你需要:
$message.unbind('click');
之前:
$message.stop(true, true).show(1000).click(function(e) {
即:
else if (displayed == false) {
displayed = true;
$message.unbind('click');
$message.stop(true, true).show(1000).click(function(e) {
...
如果您不相信我,请通过执行几次“转到顶部”使其卡住,然后在 Firebug 控制台中写入以下内容:
$('#message a').unbind('click');
然后再试一次。您将看到卡住消失了(直到您通过“点击”事件的多个绑定(bind)再次累积卡住)。
干杯。
关于jquery滚动到顶部动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13807793/