Javascript - window.scroll({behavior:'smooth'})在Safari中不起作用

问题描述 投票:7回答:2

正如标题所说,它在Chrome上运行得非常好。但在Safari中,它只是将页面设置为所需的顶部和左侧位置。这是预期的行为吗?有没有办法使它很好地工作?

javascript safari
2个回答
4
投票

IE / Edge / Safari不完全支持行为选项,因此您必须自己实现某些功能。我相信jQuery已经有了一些东西,但如果你不使用jQuery,这里是一个纯粹的Javascript实现:

function SmoothVerticalScrolling(e, time, where) {
    var eTop = e.getBoundingClientRect().top;
    var eAmt = eTop / 100;
    var curTime = 0;
    while (curTime <= time) {
        window.setTimeout(SVS_B, curTime, eAmt, where);
        curTime += time / 100;
    }
}

function SVS_B(eAmt, where) {
    if(where == "center" || where == "")
        window.scrollBy(0, eAmt / 2);
    if (where == "top")
        window.scrollBy(0, eAmt);
}

如果你需要水平滚动:

function SmoothHorizontalScrolling(e, time, amount, start) {
    var eAmt = amount / 100;
    var curTime = 0;
    var scrollCounter = 0;
    while (curTime <= time) {
        window.setTimeout(SHS_B, curTime, e, scrollCounter, eAmt, start);
        curTime += time / 100;
        scrollCounter++;
    }
}

function SHS_B(e, sc, eAmt, start) {
    e.scrollLeft = (eAmt * sc) + start;
}

一个例子是:

SmoothVerticalScrolling(myelement, 275, "center");

2
投票

使用smootscroll polyfill(适用于所有浏览器的解决方案),易于应用和轻量级依赖:https://github.com/iamdustan/smoothscroll

通过npm或yarn安装后,将其添加到主.js,.ts文件(首先执行的文件)中

import smoothscroll from 'smoothscroll-polyfill';
// or if linting/typescript complains
import * as smoothscroll from 'smoothscroll-polyfill';

// kick off the polyfill!
smoothscroll.polyfill();
© www.soinside.com 2019 - 2024. All rights reserved.