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。
问题:
针对 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)
我已经在我的项目中尝试过这种方法并且它有效,我希望你觉得这有帮助。
您所要做的只是从文件中删除'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)
请尝试一次,希望您能解决您的问题。
| 归档时间: |
|
| 查看次数: |
479 次 |
| 最近记录: |