如何具有平滑效果的

如何具有平滑效果的

本文介绍了如何具有平滑效果的 window.scrollTo()的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

解决方案

2018 更新

现在你可以只使用 window.scrollTo({ top: 0, behavior: 'smooth' }) 来让页面滚动得更流畅.

const btn = document.getElementById('elem');btn.addEventListener('click', () => window.scrollTo({顶部:400,行为:平稳",}));
#x {高度:1000px;背景:浅蓝色;}

<button id='elem'>点击滚动</button>

较旧的解决方案

你可以这样做:

var btn = document.getElementById('x');btn.addEventListener("点击", function() {变量 i = 10;var int = setInterval(function() {window.scrollTo(0, i);我 += 10;如果 (i >= 200) clearInterval(int);}, 20);})
body {背景:#3a2613;高度:600px;}

ES6 递归方法:

const btn = document.getElementById('elem');const smoothScroll = (h) =>{让 i = h ||0;如果 (i  {window.scrollTo(0, i);平滑滚动(我+ 10);}, 10);}}btn.addEventListener('click', () => smoothScroll());
body {背景:#9a6432;高度:600px;}

I can scroll to 200px using the following

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

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

解决方案

2018 Update

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

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>

ES6 recursive approach:

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>

这篇关于如何具有平滑效果的 window.scrollTo()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-12 08:19