编程语言
首页 > 编程语言> > javascript – 使用barba.js在新页面中将滚动位置设置为顶部

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

作者:互联网

我使用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中,向下滚动并按链接到页面B.页面B进入并在顶部有滚动位置
>按后退按钮,页面B滚动到页面A的位置,然后淡出
>页面A进入并在顶部有滚动位置
>向下滚动并按前进按钮.页面A滚动到顶部然后淡出
>页面B进入并在顶部有滚动位置

以下是预期的行为:

>在页面A中,向下滚动并按链接到页面B.页面B进入并在顶部有滚动位置
>按后退按钮,页面B淡出而不滚动
>页面A进入并具有滚动位置作为步骤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();
    });

标签:javascript,pjax
来源: https://codeday.me/bug/20190701/1349731.html