基于vue监听滚动事件,实现锚点内容平滑滚动,动态修改锚点状态

本文介绍了如何在Vue项目中利用滚动事件监听实现锚点链接的平滑滚动效果,并动态修改锚点状态。场景为报告目录与内容的同步滚动,当点击目录或内容滚动时,相应锚点能正确高亮并准确定位。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

基于vue监听滚动事件,实现锚点链接平滑滚动,动态修改锚点状态,锚点定位(双向)

项目场景:报告目录内容框滚动,动态修改目录章节的锚点状态,点击目录章节的锚点,滚动到目标内容

项目场景实例图
项目场景实例

点击右边对应的章节,左边内容区域滚动到对应内容区域
左边内容区域滚动内容,右边的章节锚点动态修改

问题描述:

内容平滑滚动,瞄点状态修改,监听内容高度,滚动距离

解决方案:

//左侧内容框
<div>
  <h2>{
   {
   result.name}}</h2>
  <ul>
    <li v-for="(item,i) in rep_tab_cont" :key="i" :index="item.id" class="jump">
      <h3>{
   {
   item.title}}</h3>
      <pre>{
   {
   item.content}}</pre>
    </li>
  </ul>
</div>
//右侧目录章节
<div class="float_fixed">
     <p class="title">目录章节</p>
      <ul>
        <li 
        :class
Vue实现滚动监听,可以通过以下步骤: 1. 在需要监听滚动的容器上,绑定 `@scroll` 事件。 2. 通过 `getBoundingClientRect()` 方法获取每个元素的位置信息,得到它们距离容器顶部的距离。 3.滚动事件处理函数中,获取当前容器滚动的距离,并与每个元素的位置信息进行比较,判断当前容器滚动到了哪个的位置。 4.滚动到的信息保存在 Vue 实例的数据中,并在模板中根据该数据展示对应的内容。 以下是一个简单的示例代码: ```vue <template> <div class="scroll-container" @scroll="handleScroll"> <div class="section" v-for="(section, index) in sections" :key="index"> <h2>{{ section.title }}</h2> <p>{{ section.content }}</p> </div> </div> </template> <script> export default { data() { return { activeSection: 0, // 默认选中第一个 sections: [ { title: "Section 1", content: "Content 1" }, { title: "Section 2", content: "Content 2" }, { title: "Section 3", content: "Content 3" }, { title: "Section 4", content: "Content 4" }, ], }; }, mounted() { this.calculatePositions(); }, methods: { calculatePositions() { // 获取每个元素的位置信息 this.positions = this.sections.map((section) => { const element = document.getElementById(section.title); return { title: section.title, top: element.getBoundingClientRect().top + this.$refs.container.scrollTop, }; }); }, handleScroll() { const scrollTop = this.$refs.container.scrollTop; // 判断当前滚动到了哪个 for (let i = 0; i < this.positions.length; i++) { const position = this.positions[i]; if (scrollTop >= position.top && scrollTop < position.top + 400) { this.activeSection = i; break; } } }, }, }; </script> ``` 在该示例中,使用 `getBoundingClientRect()` 方法获取每个元素的位置信息,并保存在 `positions` 数组中。在滚动事件处理函数中,获取当前容器滚动的距离,并与每个元素的位置信息进行比较,判断当前容器滚动到了哪个的位置。最后将滚动到的信息保存在 `activeSection` 中,用于在模板中展示对应的内容
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值