vue 实现滚动导航

效果

实现

css 使用了 unocss

使界面滚动到给定元素的指定坐标位置

js 复制代码
window.scrollTo({ top: 0 })

使用了内边距避免最后数据高度不够

html 复制代码
<main class="pb-100vh"></main>

完整代码

ts 复制代码
<script lang="ts" setup>
defineOptions({ name: 'DemoView' })
/** dom */
const itemRefs = ref<HTMLElement[]>([])

/** 导航列表数据 */
const navList = ['导航一', '导航二', '导航三', '导航四', '导航五']

/** 导航的索引 */
const activeIndex = ref(0)

/**
 * 切换导航
 * @param index 点击的索引
 */
function handleNav(index: number) {
  activeIndex.value = index
  scrollTo({ top: itemRefs.value[index]?.offsetTop })
}

/**
 * 监听滚动方法
 */
function onScroll() {
  const offsetTopArr: number[] = []
  itemRefs.value?.forEach((item) => {
    offsetTopArr.push((item as HTMLElement)?.offsetTop)
  })

  const scrollTop = document.documentElement.scrollTop || document.body.scrollTop

  let navIndex = 0
  for (let n = 0; n < offsetTopArr.length; n++) {
    // 如果 scrollTop 大于等于第n个元素的 offsetTop 则说明 n-1 的内容已经完全不可见
    // 那么此时导航索引就应该是n了
    if (scrollTop >= offsetTopArr[n]) {
      navIndex = n
    }
  }
  activeIndex.value = navIndex
}

onMounted(() => {
  window.addEventListener('scroll', onScroll, false)
})
onUnmounted(() => {
  window.removeEventListener('scroll', onScroll)
})

/**
 * 封装滚动到指定位置的方法
 * @param param0
 */
function scrollTo({
  top = 0,
  behavior = 'smooth'
}: {
  top?: number | undefined
  behavior?: ScrollBehavior
}) {
  window.scrollTo({
    top,
    behavior
  })
}
</script>

<template>
  <div class="pl-150px">
    <nav class="fixed left-0px top-80px">
      <ul>
        <template v-for="(nav, index) of navList" :key="index">
          <li
            class="py-30px text-[#666] cursor-pointer"
            :class="{ active: activeIndex === index }"
            @click="handleNav(index)"
          >
            {{ nav }}
          </li>
        </template>
      </ul>
    </nav>

    <main class="pb-100vh">
      <template v-for="(nav, index) of navList" :key="index">
        <div ref="itemRefs" class="h-200px w-200px mb-20px pb-30px bg-blue-700 text-white">
          {{ nav }}
        </div>
      </template>
    </main>
  </div>
</template>

<style lang="scss" scoped>
li {
  list-style: none;
}

.active {
  @apply text-blue-700 font-bold;
}
</style>
相关推荐
wuk99812 分钟前
梁非线性动力学方程MATLAB编程实现
前端·javascript·matlab
Irene199113 分钟前
在 Vue 中使用 TypeScript 的几种方式
vue.js·typescript
XiaoYu200223 分钟前
第11章 LangChain
前端·javascript·langchain
霉运全滚蛋好运围着转1 小时前
启动 Taro 4 项目报错:Error: The specified module could not be found.
前端
cxxcode1 小时前
前端模块化发展
前端
不务正业的前端学徒1 小时前
docker+nginx部署
前端
不务正业的前端学徒1 小时前
webpack/vite配置
前端
hhcccchh1 小时前
学习vue第八天 Vue3 模板语法和内置指令 - 简单入门
前端·vue.js·学习
yyf198905251 小时前
Vue 框架相关中文文献
前端·javascript·vue.js
粥里有勺糖1 小时前
开发一个美观的 VitePress 图片预览插件
前端·vue.js·vitepress