Javascript - window.scroll({behavior:'smooth'})在Safari中不起作用 [英] Javascript - window.scroll({ behavior: 'smooth' }) not working in Safari

查看:151
本文介绍了Javascript - window.scroll({behavior:'smooth'})在Safari中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

As the title says, it works perfectly fine on Chrome. But in Safari, it just sets the page to the desired top and and left position. Is this an expected behaviour? Is there a way to make it work nicely?

推荐答案

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

Behavior options aren't fully supported in IE/Edge/Safari, so you'd have to implement something on your own. I believe jQuery has something already, but if you're not using jQuery, here's a pure Javascript implementation:

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");

这篇关于Javascript - window.scroll({behavior:'smooth'})在Safari中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆