vue里的锚点定位

本文介绍了一个使用Vue.js实现的时间轴组件案例,通过点击不同的时间点,页面会滚动到对应的内容区域。此示例展示了如何结合Vue.js的声明式渲染和DOM操作来提升用户体验。

例子代码

<template>
  <div class="hello">
    <div class="all" >
      <div class="left">
        <el-timeline>
          <el-timeline-item v-for="(fatherItem, index) in allData" :key="index">
            <a @click="jump(index)">
              {{ fatherItem.moduleName }}
            </a>
          </el-timeline-item>
        </el-timeline>
      </div>
      <div class="right" ref="helloData">
        <div v-for="(fatherItem, index) in allData" :key="'a' + index">
          <div class="firsttitle">{{ fatherItem.moduleName }}</div>
          <div class="zhan-wei"></div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
export default {
  name: "HelloWorld",
  data() {
    return {
      msg: "Welcome to Your Vue.js App",
      allData: [
        {
          moduleName: "家庭成员0",
        },
        {
          moduleName: "家庭成员1",
        },
        {
          moduleName: "家庭成员2",
        },
        {
          moduleName: "家庭成员3",
        },
        {
          moduleName: "家庭成员4",
        },
        {
          moduleName: "家庭成员5",
        },
        {
          moduleName: "家庭成员6",
        },
        {
          moduleName: "家庭成员7",
        },
        {
          moduleName: "家庭成员8",
        },
        {
          moduleName: "家庭成员9",
        },
        {
          moduleName: "家庭成员10",
        },
      ],
    };
  },
  methods: {
    jump(index) {
      let jump = document.querySelectorAll(".firsttitle");
      let topUp = jump[index].offsetTop;
      window.scrollTo(0, topUp);
    },
  },
};
</script>

<!-- Add "scoped" attribute to limit CSS to this component only -->
<style scoped>
.all {
  display: flex;
}
.left {
  width: 300px;
  position:fixed;
}
.right {
  flex: 1;
  padding-left: 300px;
}
.zhan-wei {
  height: 300px;
  background-color: pink;
  border: 2px solid #ddd;
}
</style>

### Vue3 中实现点定位功能 在 Vue3 中实现点定位功能可以通过多种方式完成,既可以利用原生 HTML 点机制,也可以通过 JavaScript 动态控制滚动行为。以下是基于引用中的方法以及 Vue 的特性所提供的解决方案。 #### 方法一:使用 CSS 和 HTML 原生支持 可以按照引用描述的方式设置 `position: relative` 和 `position: absolute` 来调整点的位置[^1]。这种方式简单易用,适合静态页面场景。 HTML 结构如下: ```html <div class="anchor-container"> <h2 id="section1">Section 1</h2> <p>Content of section 1...</p> <h2 id="section2">Section 2</h2> <p>Content of section 2...</p> <h2 id="section3">Section 3</h2> <p>Content of section 3...</p> </div> ``` CSS 设置: ```css .anchor-container { position: relative; } #section1, #section2, #section3 { position: absolute; } #section1 { top: 83px; } #section2 { top: 400px; } #section3 { top: 700px; } ``` 此方法适用于简单的页面结构,但如果需要动态计算偏移量,则需借助 JavaScriptVue 的能力。 --- #### 方法二:Vue3 配合 ScrollBehavior 插件 对于更复杂的场景,推荐使用 Vue Router 提供的 `scrollBehavior` 功能来处理点跳转并自定义滚动逻辑。 配置路由文件 (`router/index.js`) 如下: ```javascript import { createRouter, createWebHistory } from 'vue-router'; const routes = [ { path: '/', component: () => import('@/views/Home.vue') }, ]; const router = createRouter({ history: createWebHistory(), routes, scrollBehavior(to, from, savedPosition) { if (to.hash) { return new Promise((resolve) => { setTimeout(() => { const element = document.querySelector(to.hash); if (element) { window.scrollTo({ top: element.offsetTop - 83, // 调整顶部偏移量 behavior: 'smooth', }); } resolve(); }, 100); // 等待 DOM 渲染完成 }); } return savedPosition || { top: 0 }; }, }); export default router; ``` 在此示例中,当 URL 包含哈希值(如 `/#section1`),会自动找到对应的元素并通过平滑滚动到达目标位置,同时减去固定的头部高度作为偏移量。 --- #### 方法三:纯前端实现动态点跳转 如果不需要依赖 Vue Router,可以直接监听点击事件,在组件内部手动触发滚动操作。 模板部分: ```html <template> <div> <nav> <button @click="navigateTo('section1')">Go to Section 1</button> <button @click="navigateTo('section2')">Go to Section 2</button> <button @click="navigateTo('section3')">Go to Section 3</button> </nav> <main> <section ref="section1" id="section1"><h2>Section 1</h2></section> <section ref="section2" id="section2"><h2>Section 2</h2></section> <section ref="section3" id="section3"><h2>Section 3</h2></section> </main> </div> </template> ``` 脚本部分: ```javascript <script setup> import { onMounted } from 'vue'; function navigateTo(targetId) { const targetElement = document.getElementById(targetId); if (targetElement) { window.scrollTo({ top: targetElement.getBoundingClientRect().top + window.scrollY - 83, // 减去固定偏移量 behavior: 'smooth', }); } } </script> ``` 这种方法完全独立于路由模块,灵活性更高,尤其适合单页应用内的局部导航需求。 --- ### 总结 以上三种方法分别针对不同复杂度的需求提供了相应的解决方案。如果是基础项目,可以选择 **方法一**;如果涉及 Vue Router 并希望全局统一管理滚动状态,建议采用 **方法二**;而对于轻量化、无路由依赖的应用,可选用 **方法三**。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值