vue3 点击目录内容滚动到最顶部

本文介绍了如何使用Vue.js构建一个具有动态目录的网页,点击目录项时平滑滚动到对应的内容区域。代码展示了利用ref和事件监听实现导航及滚动效果的实现过程。
摘要由CSDN通过智能技术生成
<template>
    <div>
      <ul class="directory">
        <li v-for="item in directory" :key="item.id" @click="scrollToSection(item.id)">
          {{ item.title }}
        </li>
      </ul>
  
      <div ref="pageContent" class="page-content">
        <div v-for="section in directory" :key="section.id" :id="section.id" class="section">
          <h2>{{ section.title }}</h2>
    
        </div>
      </div>
    </div>
  </template>
  
  <script setup>
  import { ref, onMounted } from 'vue';
  const pageContent = ref(null);
      const directory = [
        { id: 'section1', title: '标题 1' },
        { id: 'section2', title: '标题 2' },
        { id: 'section3', title: '标题 3' },
        // ... 其他目录项
      ];
  
      const scrollToSection = (sectionId) => {
        console.log(sectionId);
        const targetSection = pageContent.value.querySelector(`#${sectionId}`);//"这个id不能时数字"
        console.log(targetSection);
        if (targetSection) {
          targetSection.scrollIntoView({ behavior: 'smooth' });
        }
      };
  </script>
  
  <style>
  .directory {
    list-style: none;
    padding: 0;
  }
  
  .directory li {
    cursor: pointer;
    margin-bottom: 5px;
  }
  
  .page-content {
    padding: 20px;
    
  }
  
  .section {
    margin-bottom: 40px;
    height: 1000px;
    background-color: pink;
  }
  </style>
   


点击标题2

注意!!!!整体内容高度不够时无法滚动

  • 8
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值