JS平滑滚动

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

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容