0 前言
本文用简单的<a>
标签实现页面内、跨页面的锚点跳转。
更复杂的含有跳转、滚动动画的锚点跳转,本文中尚未更新。
1 原理说明
- 在要跳转处,添加
<a href="#anchor-specific"> anchor from </a>
标签 - 在锚点出,添加
<div id="anchor-specific"> anchor to<div>
id
每个以 # 开头的链接 href 值都指向拥有相应 id (不含 #) 的元素
点击<a>
标签,即可实现锚点跳转
2 代码实现
2.1 页面内
3_Anchor.vue
中
<template>
<div>
<ul>
<li>
<a href="#anchor-a">1</a>
</li>
<li>
<a href="#anchor-b">2</a>
</li>
<li>
<a href="#anchor-c">3</a>
</li>
<li>
<a href="#anchor-d">4</a>
</li>
</ul>
</div>
<div>
<div id="anchor-a" class="big-block">
<h1>a</h1>
</div>
<div id="anchor-b" class="big-block">
<h1>b</h1>
</div>
<div id="anchor-c" class="big-block">
<h1>c</h1>
</div>
<div id="anchor-d" class="big-block">
<h1>d</h1>
</div>
</div>
</template>
<script>
export default {
name: "3_Anchor"
}
</script>
<style scoped>
.big-block{
width: 400px;
height: 600px;
background-color: lightblue;
}
</style>
2.2 跨页面
4_JumpAnchor.vue
中
<template>
<div>
<a href="/anchor#anchor-b">
<h3>jump anchor to '/anchor#anchor-b'</h3>
</a>
</div>
</template>
<script>
export default {
name: "4_JumpAnchor"
}
</script>
<style scoped>
</style>
3 注意
建议Vue3中使用history模式,而不是hash模式。
const router = createRouter({
history: createWebHistory(),
//history: createWebHashHistory(),
routes,
})
hash模式中,#
被占用,<a>
标签的锚点跳转失效,需要使用js的方法进行跳转(window.scrollTo(x,y)像素跳转、Element.scrollIntoView()元素可见)。
您可以参考:vue项目hash路由锚点定位问题
4 参考
《HTML5与CSS3基础教程(第8版)》