实现Vue导航栏的滑动切换居中

要实现Vue导航栏的滑动切换居中,并且导航栏超出部分可以滑动,并点击触发滑动到对应的索引,可以按照以下步骤进行:

  1. 在Vue组件中,设置一个变量来存储当前选中的导航项索引。例如,命名为activeIndex,初始值为0。
<template>
  <nav class="navbar">
    <ul class="nav-list" ref="navList" :style="{ transform: `translateX(${-activeIndex * itemWidth}px)` }">
      <li class="nav-item" v-for="(item, index) in navItems" :key="index" :class="{ active: index === activeIndex }" @click="handleClick(index)">{{ item }}</li>
    </ul>
  </nav>
</template>

<script>
export default {
  data() {
    return {
      activeIndex: 0,
      navItems: ['Home', 'About', 'Services', 'Contact', 'Home', 'About', 'Services', 'Contact'],
      itemWidth: 0
    }
  },
  mounted() {
    this.itemWidth = this.$refs.navList.clientWidth / this.navItems.length
  },
  methods: {
    handleClick(index) {
      this.activeIndex = index
    }
  }
}
</script>

<style>
.navbar {
  overflow-x: auto;
}

.nav-list {
  display: flex;
  list-style: none;
  padding: 0;
  transition: transform 0.3s ease-in-out;
}

.nav-item {
  margin-right: 20px;
  font-weight: bold;
  cursor: pointer;
}

.nav-item.active {
  color: blue;
}
</style>

在上述代码中,导航栏的滑动效果通过设置transform属性实现。导航栏的滑动容器使用ref属性引用为navList,然后根据activeIndex和每个导航项的宽度itemWidth计算出滑动的距离,并通过transform属性应用于滑动容器。

点击导航项时,调用handleClick方法更新activeIndex的值,从而实现点击触发滑动到对应的索引。

通过给选中的导航项添加.active类来突出显示当前选中的项。

最后,在导航栏的样式中,设置overflow-x: auto;来允许导航栏超出部分可以水平滑动。

这样,当导航栏超出容器宽度时,用户可以通过滑动来查看其他导航项,点击导航项会触发滑动到对应的索引,并且滑动时导航栏会自动对应高亮显示。根据实际需求和设计风格,你可以对样式和交互效果进行调整和定制化。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值