背景:项目中使用了hash路由,但是又需要使用锚点定位,从而产生冲突
解决:手动获取元素使用scrollIntoView方法
function MyLink({id, children}) {
const onClick = (e) => {
e.preventDefault();
const element = document.getElementById(id);
// scrollIntoView()将目标元素移动到浏览器顶部
// scrollIntoView(false)将目标元素移动到浏览器底部
element.scrollIntoView();
}
return <a onClick={onClick}>{children} </a>
}
element.scrollIntoView(); // 等同于element.scrollIntoView(true)
element.scrollIntoView(alignToTop); // Boolean型参数
element.scrollIntoView(scrollIntoViewOptions); // Object型参数
参数:
alignToTop: 一个boolean值
true:等价于 scrollIntoViewOptions: {block: “start”, inline: “nearest”}
false:等价于scrollIntoViewOptions: {block: “end”, inline: “nearest”}
scrollIntoViewOptions: 对象
behavior: 定义动画过度效果, ‘auto / smooth’ , 默认 ‘auto’
block:定义垂直方向的对齐, “start / center / end / nearest”。默认为 “start”。
inline 定义水平方向的对齐, “start / center / end / nearest”。默认为 “nearest”
总结:使用DOM元素的scrollIntoView
方法来代替锚点定位