近期在重构集团官网的项目,遇到一个锚点跳转的疑问,在解决这个问题之前我的理解一直都是认为跨组件的锚点跳转跟不使用组件的跳转是不一样的,跨组件锚点跳转应该涉及到组件之间的传值因为在此之前没有做过这种跨组件的跳转所以我一直深以为然,显然这种想法是错误的。锚点跳转并不受组件的约束。
解决方法
锚点跳转,点击对应的按钮或者文字使页面平滑的滚动到对应的内容,属于页面的滚动。
1.使用 a 标签
通过给 a 标签的herf属性绑定对应id就可以通过点击对应的 a 标签达到跳转的效果
// a 标签锚点
<a herf="#more">跳转到more内容</a>
// more内容
<div id="more">more</div>
缺点也很明显就是改变url
2.使用 JS 的 window.location.hash
设置一个监听事件,并将window.location.hash的值设为要跳转的元素的id值就可以达到锚点跳转的功能
// 点击链接时触发跳转到锚点
document.getElementById('link').addEventListener('click', function() {
window.location.hash = '#section1';
});
// 监听 hashchange 事件,当 hash 值发生变化时,自动滚动到对应的锚点位置
window.addEventListener('hashchange', function() {
scrollToAnchor();
});
// 滚动到指定的锚点位置
function scrollToAnchor() {
const hash = window.location.hash;
if (hash) {
const targetElement = document.querySelector(hash);
if (targetElement) {
targetElement.scrollIntoView({
behavior: 'smooth'
});
}
}
}
这个方法的缺点跟使用 a 标签类似,也是会改变 url
3.使用 window.scrollTo()
scrollToEle(ele, diff=-50) {
if(ele) {
const toEl = document.querySelector(ele)
let bridge = toEl;
let body = document.body;
let height = 0;
do {
height += bridge.offsetTop;
bridge = bridge.offsetParent;
} while (bridge !== body)
window.scrollTo({
top: height + diff,
behavior: 'smooth'
})
}
}
这个方法通过偏移量 offsetTop 来计算位置,并通过 window.scrollTo() 来进行跳转
也可以通过偏移量 offset 的另一个方法 getBoundingClientRect() 来进行跳转
anchor(anchorName) {
let anchorElement = document.getElementById(anchorName);
if (anchorElement) {
const offset = 220
const bodyRect = document.body.getBoundingClientRect().top
const elementRect = anchorElement.getBoundingClientRect().top
const elementPosition = elementRect - bodyRect
const offsetPosition = elementPosition - offset
window.scrollTo({
top: offsetPosition,
behavior: "smooth"
})
}
}
两个方法,上面一个是前辈疯转的,可以动态调整偏移量的,下面这个是我自己写的,偏移量固定不变。
总结:
多学多看才能打破自己固有的认知,向前辈学习,虚心请教才能受益匪浅。