Javascript 如何具有平滑效果的 window.scrollTo()

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42261524/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 01:01:26  来源:igfitidea点击:

How to window.scrollTo() with a smooth effect

javascripthtmlcssvanilla-typescript

提问by KolaCaine

I can scroll to 200px using the following

我可以使用以下方法滚动到 200px

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

But I want a smooth scroll effect. How do I do this?

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

回答by kind user

2018 Update

2018 更新

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' })to get the page scrolled with a smooth effect.

现在,您可以使用 justwindow.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>

Older solutions

较旧的解决方案

You can do something like this:

你可以这样做:

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>

ES6recursive approach:

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>

回答by Myco Claro

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

You can do this!

你可以这样做!