如何使基于 Chromium 的浏览器上的 Element.scrollIntoView() 不依赖于平滑滚动标志?

lig*_*ght 5 javascript chromium smooth-scrolling

我有一个 JavaScript 函数,它尝试将元素平滑地滚动到视图中:

dom_element.scrollIntoView({
    'behavior': 'smooth',
    'block': 'nearest'
});
Run Code Online (Sandbox Code Playgroud)

在 Firefox 上,这工作得很好。

但我意识到滚动是即时的,即不尊重behaviour': 'smooth'基于 Chromium 的浏览器(Chrome、Opera、Brave)。

MDN 和 caniuse.com 都显示 Chrome 支持behaviour: smooth,所以我很困惑。

经过令人沮丧的一小时调试后,我意识到如果我专门转到将Smooth Scrolling从Defaultchrome://flags/#smooth-scrolling切换到Enabled,代码就可以工作。经过一些实验,我推断出平滑滚动的Default 值意味着Disabled。

奇怪的是:在另一台计算机(笔记本电脑)上,上面的代码按预期工作,无需调整Smooth Scrolling。它被保留为默认值,滚动很流畅。

两台电脑都在 Win 10 Pro 上运行最新的 Chrome v83.0.4103.61。

问题:

  1. 为什么两台计算机的平滑滚动标志的默认设置不同?如果硬件很重要,一个是带有 nVidia 1060GT 的台式机 i7-6700K,另一个是带有 GeForce MX110 的笔记本电脑 i7-8550U。
  2. 由于在使用站点之前告诉用户启用此标志是不切实际的,是否可以在 JS 中以编程方式覆盖此标志?

针对 Chrome 上的某些PC演示此问题的代码段:

dom_element.scrollIntoView({
    'behavior': 'smooth',
    'block': 'nearest'
});
Run Code Online (Sandbox Code Playgroud)
let dom_target = document.querySelector('#target');

// Make clicks anywhere scroll smoothly to target (number 14)
document.addEventListener('click', function() {
    dom_target.scrollIntoView({
        'behavior': 'smooth',
        'block': 'nearest'
    });
});
Run Code Online (Sandbox Code Playgroud)
#container {
  overflow: scroll;
  border: 1px solid #333;
}

.item {
  border: 1px solid #333;
  height: 100px;
  background-color: red;
  text-align: center;
  color: white;
  font-size: 40px;
  line-height: 100px;
}

#target {
  background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)

Kai*_*ido 6

你不能。1

这由辅助功能设置控制,您可以从Windows“设置 > 轻松访问 > 显示”中的“在 Windows 中显示动画”设置触发。

这是操作系统的可访问性功能,浏览器不会让您的网站覆盖它。

(另请注意,您提到的标志可能会被删除,以支持仅让此设置控制此行为,因此将来它甚至可能不是可能的解决方法)。

但这应该不是问题,因为使用此设置的用户确实有充分的理由进行设置。

1:当然你可以手动制作,但实际上你不应该违背用户的喜好。


Min*_*hah 1

我已经在我的项目中尝试过这种方法并且它有效,我希望你觉得这有帮助。

您所要做的只是从文件中删除'behavior': 'smooth' 。所以你的代码应该如下所示:

let dom_target = document.querySelector('#target');

// Make clicks anywhere scroll smoothly to target (number 14)
document.addEventListener('click', function() {
dom_target.scrollIntoView({
    'block': 'nearest'
 });
});
Run Code Online (Sandbox Code Playgroud)

您只需将样式scroll-behavior: smooth添加到带有 id target 的元素即可。

所以你的 HTML 文件应该是这样的:

<h1>Clicking anywhere scrolls to 14, and the scrolling behavior should be smooth.</h1>
<section id="container">
<div class="item">1</div>
<div class="item">2</div>
<div class="item">3</div>
<div class="item">4</div>
<div class="item">5</div>
<div class="item">6</div>
<div class="item">7</div>
<div class="item">8</div>
<div class="item">9</div>
<div class="item">10</div>
<div class="item">11</div>
<div class="item">12</div>
<div class="item">13</div>
<div class="item" id="target" style="scroll-behavior:'smooth'">14</div>
<div class="item">15</div>
<div class="item">16</div> 
</section>
Run Code Online (Sandbox Code Playgroud)

请尝试一次,希望您能解决您的问题。