vue实现锚点定位

859 阅读1分钟

在Vue项目中,vue-router 用的是 hash 模式,不能使用传统 a 标签的方式来做锚点定位

经某度查找发现scrollIntoView()可实现

// 动画过渡效果  behavior: "auto" 或 "smooth" 默认为 "auto"
// 垂直方向对齐  block: "start", "center", "end", 或 "nearest" 默认为 "start"
// 水平方向对齐  inline: "start", "center", "end", 或 "nearest" 默认为 "nearest"

document.getElementById(id).scrollIntoView({
 behavior: 'smooth',
 block: 'start',
 inline: 'nearest'
})
// false === {block: "end", inline: "nearest"}  
// true === {block: "start", inline: "nearest"}
document.getElementById(id).scrollIntoView(false); 

Element.scrollIntoView() - Web API 接口参考 | MDN