【前端】HTML锚点跳转实现

0 前言

本文用简单的<a>标签实现页面内、跨页面的锚点跳转。
更复杂的含有跳转、滚动动画的锚点跳转,本文中尚未更新。


1 原理说明

  1. 在要跳转处,添加<a href="#anchor-specific"> anchor from </a>标签
  2. 在锚点出,添加<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版)》

  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值