如何以平滑的效果window.scrollTo() [英] How to window.scrollTo() with a smooth effect

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

问题描述

我可以通过以下方式滚动到200px。

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

但我想要一个平滑的滚动效果。如何做到这一点?

解决方案

您可以这样做:

< pre-class =snippet-code-js lang-js prettyprint-override> 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);}) {background:#3a2613; height:600px;}

< button id ='x '>点击< /按钮>

ES6 递归方法:
$ b

const btn = document.getElementById('elem '); const smoothScroll =(h)=> {让我= h || 0;如果(i <200){setTimeout(()=> {window.scrollTo(0,i); smoothScroll(i + 10);},10); }} btn.addEventListener('click',()=> smoothScroll());

  body {background:#9a6432; height:600px;}  

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


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?

解决方案

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()的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆