我使用barba.js文档中的代码如下所示切换页面。
var FadeTransition = Barba.BaseTransition.extend({
start: function() {
Promise
.all([this.newContainerLoading, this.fadeOut()])
.then(this.fadeIn.bind(this));
},
fadeOut: function() {
return $(this.oldContainer).animate({ opacity: 0 }).promise();
},
fadeIn: function() {
var _this = this;
var $el = $(this.newContainer);
$(this.oldContainer).hide();
$el.css({
visibility : 'visible',
opacity : 0
});
$el.animate({ opacity: 1 }, 400, function() {
_this.done();
});
}
});
Barba.Pjax.getTransition = function() {
return FadeTransition;
};
问题是滚动位置保留在新页面中。 我试着添加$(window).scrollTop(0);在fadeIn功能中,但这会在按下后退按钮时产生不需要的滚动。怎么解决?
以下是添加$(window).scrollTop(0);
后的行为以下是预期的行为:
答案 0 :(得分:2)
Barba.Dispatcher.on('newPageReady', function(current, prev, container) {
history.scrollRestoration = 'manual';
});
添加此解决了跳跃问题。但是,这会丢失最后一页的滚动位置,即无论是进入新页面还是旧页面,都会丢失。
参考:https://github.com/luruke/barba.js/issues/133
polyfill:https://github.com/bfred-it/scroll-restoration-polyfill
答案 1 :(得分:1)
fadeIn: function() {
$(window).scrollTop(0); // scroll to top here
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();
});
答案 2 :(得分:0)
这就是我如何使用它:
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!
*/
var _this = this;
var $el = $(this.newContainer);
$(this.oldContainer).hide();
$el.css({
visibility : 'visible',
opacity : 0
});
$("html, body").animate({ scrollTop: 0 }, "slow");
$el.animate({ opacity: 1 }, 400, function() {
_this.done();
});