先介绍下API及参数:
document.querySelector('#需要定位的ID').scrollIntoView({
behavior: "smooth", // 定义动画过渡效果, "auto"或 "smooth" 之一。默认为 "auto"
block: "center", // 定义垂直方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "start"
inline: "nearest" // 定义水平方向的对齐, "start", "center", "end", 或 "nearest"之一。默认为 "nearest"
})
效果极好。
附加传统锚点跳转方式:
<div id="dom"><div/>
- 通过a标签跳转:
<a href="#dom"></a>
- 通过js跳转:
window.location.href = '#dom'