JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Vue手写tab滑动

2021. 01. 26    

vue手写Tab超出头部导航,滑动左右按钮切换

<style lang="less">
.wrap{
  white-space: nowrap;
  position: relative;
  overflow: hidden;
  height: 33px;
}
.box{
  position: relative;
  float: left;
  transition: transform 0.5s ease-in-out;
  word-spacing: -1em;
}
.item{
  display: inline-block;
  width: 86px;
  height: 33px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}
.left,
.right {
  position: absolute;
  top: 0;
  width: 19px;
  height: 33;
  z-index: 5;
}
.left {
  left: 0;
}
.right {
  right: 0;
}
</style>
<template>
  <div class="wrap" ref="wrap">
    <div class="left"  @click="leftMove" v-if="iconRight"></div>
    <div class="box" ref="box">
      <div class="item" v-for="(item,index) in list" :key="index">
        
      </div>
    </div>
    <div class="right" @click="rightMove" v-if="iconLeft"></div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      list:["哈哈","哈哈","哈哈","哈哈","哈哈","哈哈","哈哈","哈哈","哈哈","哈哈","哈哈","哈哈","哈哈",],
      boxOffLeft:0,
      iconRight: false,
      iconLeft: false,
    }
  },
  mounted() {
    //判断tab过多超出显示right
    this.showLR()
  },
  methods: {
    showLR() {
      this.$nextTick(() => {
        let WrapWidth = this.$refs.wrap.offsetWidth;
        let BoxWidth = this.$refs.box.offsetWidth;
        if (BoxWidth > WrapWidth) {
          this.iconLeft = true;
        }
      });
    },
    leftMove() {
      let WrapWidth = this.$refs.wrap.offsetWidth;
      let BoxWidth = this.$refs.box.offsetWidth;
      this.boxOffLeft += BoxWidth / this.list.length;
      if (this.boxOffLeft < 0) {
        this.$refs.box.style.transform =
          "translateX(" + this.boxOffLeft + "px)";
      } else {
        this.$refs.box.style.transform = "translateX(" + 0 + "px)";
        this.iconRight = false;
      }
      if (BoxWidth > WrapWidth) {
        this.iconLeft = true;
      }
    },
    rightMove() {
      let WrapWidth = this.$refs.wrap.offsetWidth;
      let BoxWidth = this.$refs.box.offsetWidth;
      if (BoxWidth > WrapWidth) {
        this.iconLeft = true;
      }
      this.boxOffLeft -= BoxWidth / this.list.length;
      if (BoxWidth - WrapWidth > Math.abs(this.boxOffLeft)) {
        this.$refs.box.style.transform =
          "translateX(" + this.boxOffLeft + "px)";
      } else {
        this.$refs.box.style.transform =
          "translateX(" + (WrapWidth - BoxWidth) + "px)";
        this.iconLeft = false;
      }
      if (this.boxOffLeft < 0) {
        this.iconRight = true;
      }
    },
  },
}
</script>