JS smooth scrolling

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;
}

The above code IE, Edge support is not very good, is compatible with the following wording

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' });

More Quguan network see: http://iamdustan.com/smoothscroll/
other implementations: jump.js

Guess you like

Origin blog.csdn.net/weixin_34273046/article/details/90827141