手写tab左右切换

20 篇文章 0 订阅
9 篇文章 0 订阅

效果 :点击左右两个按钮达到切换效果(利用transform 进行平移)

点击左右达到切换的效果

<div class="app">
    <div class="tab-wrap">
      <div class="tab">
        <div ref="itemWrap" class="item-wrap"  :style="{transform: `translateX(${distance}px)`}">
          <div v-for="(item,index) in 20" :key="index" class="item" :class="{active:index===tabActive}" @click="tabActive = index">
            tab {{item}}
          </div>
        </div>
      </div>
      <div class="btn left" @click="arrow(1)">left</div>
      <div class="btn right" @click="arrow(-1)">right</div>
    </div>
  </div>
  <script src="../vue.js"></script>
  <script src="./index.js"></script>
new Vue({
  el: '.app',
  data() {
    return {
      message: 'aaaaaaaaaaa',
      tabActive: 0, // 激活样式
      distance: 0, // tab 滚动(移动)的距离
    }
  },
  created() {},
  mounted() {},
  methods: {
    // 移动tab
    arrow(num) {
      const dom = this.$refs.itemWrap
      const domWidth = dom.clientWidth // 拿到当前盒子宽度
      const parentDomWidth = dom.parentNode.clientWidth // 拿到展示宽度(及父级宽度)
      if (domWidth < parentDomWidth) return
      this.distance += parentDomWidth * num * 0.6
      if (this.distance > 0) {
        this.distance = 0
      }
      const maxDistance = -(domWidth - parentDomWidth)  // 可移动最大宽度
      if (this.distance < maxDistance) {
        this.distance = maxDistance
      }
    },
  },
})
* {
  margin: 0;
  padding: 0;
  box-sizing: border-box;
}
body{
  overflow: hidden;
}
.app{
  /* color: red; */
  font-size: 16px;
  /* display: flex;
  align-items: center;
  justify-content: center; */
}
.tab-wrap{
  width: 100vw;
  height: 80px;
  padding:0 60px;
  position: relative;
  background: #f1f6fe;
}

.tab {
  overflow: hidden;
  padding-top: 20px;
  height: 100%;
  position: relative;
}
.item-wrap {
  display: flex;
  height: 100%;
  transition: transform 0.3s;
  width: max-content;  
  position: absolute;
  /* width: max-content; 将盒子宽度取所有子集的宽度之和 且不缩放*/
}
.item {
  padding: 10px 20px;
  background: #f5f5f5;
  margin-right: 10px;
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
  background: rgba(110, 158, 248, 0.1);
}
.item.active{
  background: rgba(110, 158, 248, 1);
  color: #fff;
}
.btn {
  position: absolute;
  top: 0;
  width: 50px;
  height: 100%;
  background: rgba(110, 158, 248, 0.4);
  display: flex;
  align-items: center;
  justify-content: center;
  cursor: pointer;
}
.left{
  left: 0;
}
.right{
  right: 0;
}

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值