Click on the navigation of the vue project to slide to the corresponding position

Utilize scrollIntoView()method, which scrolls the element calling it into the visible area of ​​the browser window
Note: This method is only useful when the page is scrollable

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

The parameters of the scrollInteView method are configured as follows:
insert image description here
Case:

<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>

Effect:
insert image description here

Guess you like

Origin blog.csdn.net/CYL_2021/article/details/129343603