如何用window.scrollTo()实现平滑效果

问题描述 投票:0回答:3

我可以使用以下内容滚动到 200px

btn.addEventListener("click", function(){
    window.scrollTo(0,200);
})

但我想要平滑的滚动效果。我该怎么做?

javascript css scroll css-animations css-transitions
3个回答
271
投票

2023 更新

现在您只需使用

window.scrollTo({ top: 0, behavior: 'smooth' })
即可获得平滑的页面滚动效果。

const btn = document.getElementById('elem');

btn.addEventListener('click', () => window.scrollTo({
  top: 400,
  behavior: 'smooth',
}));
#x {
  height: 1000px;
  background: lightblue;
}
<div id='x'>
  <button id='elem'>Click to scroll</button>
</div>

旧解决方案

你可以这样做:

var btn = document.getElementById('x');

btn.addEventListener("click", function() {
  var i = 10;
  var int = setInterval(function() {
    window.scrollTo(0, i);
    i += 10;
    if (i >= 200) clearInterval(int);
  }, 20);
})
body {
  background: #3a2613;
  height: 600px;
}
<button id='x'>click</button>

ES6递归方法:

const btn = document.getElementById('elem');

const smoothScroll = (h) => {
  let i = h || 0;
  if (i < 200) {
    setTimeout(() => {
      window.scrollTo(0, i);
      smoothScroll(i + 10);
    }, 10);
  }
}

btn.addEventListener('click', () => smoothScroll());
body {
  background: #9a6432;
  height: 600px;
}
<button id='elem'>click</button>


3
投票
$('html, body').animate({scrollTop:1200},'50');

你可以做到!


0
投票

你可以添加CSS

* {scroll-behavior: smooth;}
星号 prolly 表示 window idk,但它适用于我的

© www.soinside.com 2019 - 2024. All rights reserved.