使用barba.js在新页面中将滚动位置设置为顶部

时间:2017-06-28 19:38:52

标签: javascript pjax

我使用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);

后的行为
    在页面A中
  1. ,向下滚动并按链接到页面B.页面B进入并在顶部滚动位置
  2. 按后退按钮,页面B滚动到页面A的位置,然后淡出
  3. 页面A在顶部输入并具有滚动位置
  4. 向下滚动并按前进按钮。页面A滚动到顶部然后淡出
  5. 第B页进入,顶部有滚动位置
  6. 以下是预期的行为:

      在页面A中
    1. ,向下滚动并按链接到页面B.页面B进入并在顶部滚动位置
    2. 按后退按钮,页面B淡出而不滚动
    3. 页面A进入并具有滚动位置作为步骤1

3 个答案:

答案 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();
    });