【发布时间】:2017-08-06 19:17:01
【问题描述】:
滚动设置
我正在使用流行的scroll detection method 在向下滚动时隐藏nav 元素并在向上滚动时显示它。
$(window).scroll(function(){
currentScrollTop = $(window).scrollTop();
if (currentScrollTop > lastScrollTop) {
// On scroll down
$('nav').removeClass('active');
console.log('Down');
} else {
// On scroll up
$('nav').addClass('active');
console.log('Up');
}
lastScrollTop = currentScrollTop;
logScroll();
});
Barba.js 过渡
我还使用barba.js 和所有工作正常的页面转换。每次我加载一个新页面时,我都会运行一个转换,并且我还运行一些我自己的自定义函数,这些函数对滚动没有影响,除了:
$(window).scrollTop(0)
我用来向上滚动到文档的顶部。它可以跨浏览器工作。
var FadeTransition = Barba.BaseTransition.extend({
start: function() {
// This function is automatically called as soon the Transition starts
// this.newContainerLoading is a Promise for the loading of the new container
// (Barba.js also comes with an handy Promise polyfill!)
// As soon the loading is finished and the old page is faded out, let's fade the new page
Promise
.all([this.newContainerLoading, this.fadeOut()])
.then(this.fadeIn.bind(this));
},
fadeOut: function() {
// this.oldContainer is the HTMLElement of the old Container
return $(this.oldContainer).animate({ opacity: 0 }).promise();
},
fadeIn: function() {
// this.newContainer is the HTMLElement of the new Container
// At this stage newContainer is on the DOM (inside our #barba-container and with visibility: hidden)
// Please note, newContainer is available just after newContainerLoading is resolved!
// Custom — Add scrollTop
$(window).scrollTop(0);
resetScrollTop();
// Custom - History ScrollTop
if ('scrollRestoration' in history) {
history.scrollRestoration = 'manual';
}
var _this = this;
var $el = $(this.newContainer);
$(this.oldContainer).hide();
$el.css({
visibility : 'visible',
opacity : 0
});
$el.animate({ opacity: 1 }, 400, function() {
// Do not forget to call .done() as soon your transition is finished!
// .done() will automatically remove from the DOM the old Container
_this.done();
});
}
});
重置滚动
我还添加了一个同时运行的自定义函数来尝试重置所有滚动。
function resetScrollTop() {
currentScrollTop = $(this).scrollTop();
lastScrollTop = 0;
$('nav').removeClass('active');
}
我什至尝试将 currentScrollTop 设置为零,这显然会在第一次滚动时被覆盖,但这似乎没有任何效果(也没有完全删除重置功能):
currentScrollTop = 0
控制台日志
我一直在记录这两个值,以尝试确定发生了什么:
function logScroll() {
console.log(currentScrollTop + ' ' + lastScrollTop);
}
当我加载第一页并 向下滚动 通常 currentScrollTop 总是至少 lastScrollTop + 1:
但是在每次 barba 转换之后,当我 向下滚动 时,我发现 currentScrollTop 和 lastScrollTop 有时是相等的,我认为这是导致问题的原因。我只是不知道什么会导致它们同步增加:
我们将不胜感激任何帮助/想法。
【问题讨论】:
标签: javascript jquery scroll