// 点击此处
<div @click="jump">点击锚点</div>
<div class="box" ref="box_ref">
锚点内容
</div>
methods: {
jump() {
// 获取元素在页面中的位置
// console.log(this.$refs.box_ref.getBoundingClientRect());
// document
// .getElementById("agentTitle")
// .scrollIntoView({ block: "start", behavior: "smooth" });
// 跳转到指定位置并且平滑滚动
// this.$el
// .querySelector(".box")
// .scrollIntoView({ block: "start", behavior: "smooth" });
const element = this.$refs['box_ref']
element.scrollIntoView({ block: "start", behavior: "smooth" });
},
}
使用CSS的scroll-margin-top属性,在元素滚动到达时添加一个额外的距离,以避免滚动到头部fixed布局之下。例如:
.box {
scroll-margin-top: 20px;
}