vue项目点击导航滑动到相应的位置

该示例展示了如何在Vue.js中使用scrollIntoView方法,结合behavior参数实现元素从导航列表点击到内容区平滑滚动的效果。当点击导航项时,相应的内容块会缓缓滚动到视口可见区域。

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

利用scrollIntoView()方法,该方法将调用它的元素滚动到浏览器窗口的可见区域
注:此方法在页面可滚动时才有用

methods:{
    go(){
      document.getElementById("show").scrollIntoView({ behavior: 'smooth' });
    }
  }

scrollInteView方法的参数配置如下:
在这里插入图片描述
案例:

<template>
  <div class="container">
    <div class="nav">
      <ul>
        <li
          v-for="(item, index) in state.navData"
          :key="item"
          @click="go(index)"
        >
          {{ item }}
        </li>
      </ul>
    </div>
    <div class="content">
      <div class="item">1</div>
      <div class="item">2</div>
      <div class="item">3</div>
      <div class="item">4</div>
    </div>
  </div>
</template>
<script setup>
import { reactive } from "vue";
const state = reactive({
  navData: [1, 2, 3, 4],
});
const go = (index) => {
  var items = document.querySelectorAll(".item");
  //缓慢移动至目标位置
  items[index].scrollIntoView({ behavior: "smooth" });
};
</script>

效果:
在这里插入图片描述

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值