这段代码是一个基于Vue框架的组件,通过点击导航链接来实现页面滑动到指定内容,并且对应的导航链接会高亮显示。

goAnchor方法中,使用document.querySelector(selector).scrollIntoView()来实现页面滑动到指定内容。同时,将findIndex设置为当前导航链接的索引,以便在模板中设置对应导航链接的高亮样式。

在模板中,使用v-for指令遍历componentList数组,生成对应的导航链接。通过动态绑定class属性来设置导航链接的样式,当index等于findIndex时,添加nav_active类,表示高亮显示。

<template>
  <div class="main">
    <div class="navback">
      <div class="nav">
        <template v-for="(navItem, index) in componentList">
          <div
            @click.prevent="goAnchor(navItem.id, index)"
            :key="navItem.id"
            :class="{
              nav_active: index === findIndex,
              nav_item: navItem.nav_item,
              nav_other: navItem.nav_other
            }"
          >
            {{ navItem.name }}
          </div>
        </template>
      </div>
    </div>
    <!-- 页面内容 -->
  </div>
</template>

其中,nav_activenav_itemnav_other是定义的样式类,通过动态绑定来控制是否添加到对应的导航链接上。

<style lang="scss" scoped>
.nav_item {
  @include flex-center;
  flex: 1;
  font-size: 20px;
  font-weight: 400;
  line-height: 60px;
  cursor: pointer;
  color: #ffffff;
}
.nav_item:hover {
  background: #a60000;
}
.nav_active {
  background: #a60000;
}
.nav_other {
  flex: 2;
}
</style>

这样,当点击导航链接时,页面会滑动到对应的内容,并且该导航链接会高亮显示


原文地址: https://www.cveoy.top/t/topic/iEKz 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录