美文网首页
JS平滑滚动

JS平滑滚动

作者: Mica_马超 | 来源:发表于2019-05-31 09:55 被阅读0次

1.window.scrollTo()

// left 是文档中的横轴坐标。
// top 是文档中的纵轴坐标。
window.scrollTo({ 
    top: 1000, 
    left: 0,
    behavior: "smooth" 
})

or

// window.scrollTo(x, y);
// x 是文档中的横轴坐标。
// y 是文档中的纵轴坐标。
window.scrollTo(0, 1000);
html {
  scroll-behavior: smooth;
}

2.scrollIntoView

document.getElementById(id).scrollIntoView({ behavior: 'smooth' })

or

document.getElementById(id).scrollIntoView();
html {
  scroll-behavior: smooth;
}

以上代码IE、Edge 支持不是很好,下面兼容写法

3. smoothscroll

npm install smoothscroll-polyfill --save
import smoothscroll from 'smoothscroll-polyfill';

// kick off the polyfill!
smoothscroll.polyfill();

window.scroll({ top: 2500, left: 0, behavior: 'smooth' });
element.scroll({ top: 0, left: 0, behavior: 'smooth' });

document.querySelector('.hello').scrollIntoView({ behavior: 'smooth' });
document.querySelector('header').scrollIntoView({ behavior: 'smooth' });

element.scrollBy({ top: 100, left: 0, behavior: 'smooth' });

更多去官网看:http://iamdustan.com/smoothscroll/
其他实现:jump.js

相关文章

网友评论

      本文标题:JS平滑滚动

      本文链接:https://www.haomeiwen.com/subject/ianitctx.html