带有选项的window.scrollTo在Microsoft Edge上不起作用

CDK*_*CDK 3 javascript microsoft-edge

我有一个奇怪的问题,我只能在Microsoft浏览器上复制(已测试Edge和IE11)。

<style>
    body {
        height: 5000px;
        width: 5000px;
    }
</style>
<p>Click the button to scroll the document window to 1000 pixels.</p>
<button onclick="scrollWin()">Click me to scroll!</button>
<script>
    function scrollWin() {
        window.scrollTo({
            left: 1000, 
            top: 1000,
            behavior:"smooth"
        });
    }
</script>
Run Code Online (Sandbox Code Playgroud)

这段代码可以正确地将窗口向左和向下滚动1000px,在Chrome和Firefox中行为流畅。但是,在Edge和IE上,它根本不会移动。

CDK*_*CDK 9

也许不是一个真正的答案,但我已经通过使用以下有用的polyfill解决了这个问题:https : //github.com/iamdustan/smoothscroll在所有浏览器上都非常有效。

pollyfill的示例页面:http ://iamdustan.com/smoothscroll/

非常感谢作者。


nla*_*son 7

您可以使用此代码段检测对该behavior选项的支持scrollTo

function testSupportsSmoothScroll () {
  var supports = false
  try {
    var div = document.createElement('div')
    div.scrollTo({
      top: 0,
      get behavior () {
        supports = true
        return 'smooth'
      }
    })
  } catch (err) {}
  return supports
}
Run Code Online (Sandbox Code Playgroud)

在 Chrome、Firefox、Safari 和 Edge 中测试,似乎可以正常工作。如果supports为 false,您将退回到 polyfill。


eye*_*hUp 7

如前所述,“ 滚动行为”规范仅在Chrome,Firefox和Opera中实现。

这是检测以下方面对behavior属性的支持的一种方法ScrollOptions

const supportsNativeSmoothScroll = 'scrollBehavior' in document.documentElement.style;
Run Code Online (Sandbox Code Playgroud)

这是跨浏览器平滑滚动的简单实现:https : //nicegist.github.io/d210786daa23fd57db59634dd231f341