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

猜你喜欢

转载自blog.csdn.net/weixin_34273046/article/details/90827141