JAVASCRIPT
VUE
REACT
NODE
ES6
TYPESCRIPT

Vue左右点击切换

2020. 09. 11    

Vue左右点击切换

<style lang='less'>
.wrap {
  white-space: nowrap;
  position: relative;
  overflow: hidden;
}
.box {
  position: relative;
  float: left;
  transition: transform 0.5s ease-in-out;
}
.dom {
  position: relative;
  display: inline-block;
  width: 227px;
  height: 260px;
  vertical-align: top;
}
.icon {
  position: absolute;
  top: 100px;
  cursor: pointer;
}
.left {
  left: 0;
}
.right {
  right: 0;
}
</style>

<template>
  <div ref="wrap" class="wrap">
    <div ref="box">
      <div class="dom" v-for="item in list" :key="item"></div>
      <span class="icon left" @click="goleft">LEFT</span>
      <span class="icon right" @click="goright">RIGHT</span>
    </div>
  </div>
</template>

<script>
export default {
  data() {
    return {
      iconLeft: true,
      boxOffLeft: 0,
      iconRight: false,
      list: [
        {
          name: "第一块",
        },
        {
          name: "第二块",
        },
        {
          name: "第三块",
        },
      ],
    };
  },
  methods: {
    //向左移动
    goleft() {
      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;
      }
    },
    goright() {
      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;
      }
    },
  },
};
</script>