Илья Зеленьк..
20
2018年纯粹的js:
滚动到元素有一种非常方便的方法:
el.scrollIntoView({
behavior: 'smooth', // smooth scroll
block: 'start' // the upper border of the element will be aligned at the top of the visible part of the window of the scrollable area.
})
但据我了解,他没有下面的选项那么好的支持.
如果元素必须在顶部:
const element = document.querySelector('#element')
const top = element.getBoundingClientRect().top + window.pageYOffset
window.scrollTo({
top, // scroll so that the element is at the top of the view
behavior: 'smooth' // smooth scroll
})
如果您希望元素位于中心:
const element = document.querySelector('#element')
const rect = element.getBoundingClientRect() // get rects(width, height, top, etc)
const viewHeight = Math.max(document.documentElement.clientHeight, window.innerHeight || 0);
window.scroll({
top: rect.top + rect.height / 2 - viewHeight / 2,
behavior: 'smooth' // smooth scroll
});
支持:
他们写scroll的方法与方法相同scrollTo,但支持显示更好scrollTo.