vanilla JS原生滚动动画不适用于FF

时间:2017-06-22 13:08:14

标签: javascript

我有以下内容:

class FloatingBtn {
    constructor (s) {
        this.button = s.button;
    }
}

FloatingBtn.prototype.showOnScroll = function(windowPos) {
    if(windowPos > 120){
        this.button.classList.add('opacity-on');
    }
    else {
        this.button.classList.remove('opacity-on');
    }
}

//t = current time
//b = start value
//c = change in value
//d = duration
Math.easeInOutQuad = function (t, b, c, d) {
    t /= d/2;
    if (t < 1) return c/2*t*t + b;
    t--;
    return -c/2 * (t*(t-2) - 1) + b;
};

FloatingBtn.prototype.scrollTo = function(element, to, duration) {
    let start = element.scrollTop,
        change = to - start,
        currentTime = 0,
        increment = 20;

    let animateScroll = function(){        
        currentTime += increment;
        console.log(change);
        let val = Math.easeInOutQuad(currentTime, start, change, duration);
        element.scrollTop = val;
        if(currentTime < duration) {
            setTimeout(animateScroll, increment);
        }
    };
    animateScroll();
}

FloatingBtn.prototype.scrollBackToTop = function() {
    this.button.addEventListener('click', () => {
        this.scrollTo(document.body, 0, 700);
    });
}

export default FloatingBtn;

它适用于Chrome和Safari,但不适用于FF。该页面根本不会滚动到顶部。没有错误抛出到控制台。

1 个答案:

答案 0 :(得分:1)

Firefox不再支持document.body.scrollTop。相反,您必须使用document.documentElement.scrollTop

您可以更改单击处理程序以使用三元组来确定正确的元素

this.scrollTo( document.body.scrollTop == 0 ? document.documentElement : document.body, 0, 700 );

您还必须使用start

之类的内容更改scrollTo函数中的document.body.scrollTop || document.documentElement.scrollTop变量