ScrollToOptions 的行为:'smooth' 在 Chrome 和 Edge v81+ 中损坏

ScrollToOptions' behavior: 'smooth' broken in Chrome and Edge v81+

在 BrowserStack 中测试后,我得出结论,使用带有选项参数 behavior: smoothscrollTo() 在 Chrome 和自版本 81 起的 Edge 中不起作用。Edge 和 80 版本Chrome 正在按预期工作。根据 MDN,它应该在没有星号的情况下工作。 (与 Safari 不同)

this one 等热门答案中,推荐使用 behavior: smooth 来在您的 Web 应用程序中启用平滑滚动。

这是一个小的可复制的:

<html>
<button onclick="goToAnchor('b')">Scroll to B</button>
<div id="a" style="height: 1000px; background-color: blue;">Blue</div>
<div id="b" style="height: 1000px; background-color: red;">Red</div>
<div id="c" style="height: 1000px; background-color: green;">Green</div>

</html>

<script>
  function goToAnchor(anchor) {
    let rect = document.getElementById(anchor).getBoundingClientRect();
    window.scrollTo({
      left: rect.left + window.pageXOffset,
      top: rect.top + window.pageYOffset,
      behavior: 'smooth',
    });
  }
</script>

预期的行为是浏览器 window 平滑地将视图向下插入到红色 div。它在我测试过的所有版本的 Firefox 中都能正确地做到这一点。在自 v81 以来的所有 Chrome 版本以及自 v81 以来所有版本的 Edge 中,它似乎使用 behavior: auto 的行为 - 即它跳转到 div 而不是平滑地插入查看。

在 Edge 和 Chrome 的 80 版本中,它的行为与 Firefox 一样,这意味着这个错误 (?) 一定是在 81 版本中引入的——也许是在共享的 Chromium 代码库中?

我发现 非常 我不太可能是第一个发现这个问题的人,因为它自 4 月以来一直没有工作,因此必须断定我做错了什么.有人可以指出代码中的错误吗?或者 Chrome 和 Edge API 真的坏了吗?行为是否隐藏在功能标志后面,就像在 Safari 中一样?

我尝试使用 MS Edge 版本 87.0.664.60Google Chrome 版本 87.0.4280.88.

在我这边,代码在两种浏览器上都能正常工作。

这是我的测试结果:(上面是 MS Edge,下面是 Google Chrome 浏览器)

您正在使用 BrowserStack 进行此测试。该问题可能与 BrowserStack.

有关

建议您尝试使用实际浏览器进行测试。它可以帮助您找到问题的原因。

我相信我已经找到了罪魁祸首,有趣的是,Firefox 似乎是那个奇怪的人。

this Whosebug thread about detecting RDP connections, the current top answer中说:

You can use the following media query:

@media screen and (prefers-reduced-motion: reduce) { . . . }

prefers-reduced-motion 部分很有趣。在我的测试中,这似乎也改变了 scrollTo() 调用 scroll-behavior: 'smooth' 以跳转而不是插值。

我对问题的代码示例做了一个附录来演示该功能:

<html>
  <button onclick="goToAnchor('b')">Scroll to B</button>
  <p class="reduced-motion">Reduced motion is enabled.</p>
  <div id="a" style="height: 1000px; background-color: blue;">Blue</div>
  <div id="b" style="height: 1000px; background-color: red;">Red</div>
  <div id="c" style="height: 1000px; background-color: green;">Green</div>
</html>
<style>
  .reduced-motion {
    display: none;
  }
  @media (prefers-reduced-motion) {
    .reduced-motion {
      display: inline;
    }
  }
</style>
<script>
  function goToAnchor(anchor) {
    let rect = document.getElementById(anchor).getBoundingClientRect();
    window.scrollTo({
      left: rect.left + window.pageXOffset,
      top: rect.top + window.pageYOffset,
      behavior: 'smooth',
    });
  }
</script>

它现在会说“减少运动已启用”。按钮旁边,具体取决于您的 OS 和浏览器配置。在这种情况下,scrollTo 调用将简单地跳转而不是插值。

简而言之,问题是 BrowserStack 的远程桌面控件也启用了这个标志。