element轮播图支持移动端

435 阅读1分钟

代码如下

<template>
  <div class="container">
    <el-carousel ref="carousel" :autoplay="autoplay" indicator-position="outside" height="1000px">
      <el-carousel-item v-for="item in 4" :key="item">
        <h3>{{ item }}</h3>
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script>
export default {
  data() {
    return {
      autoplay: true,
    }
  },
  mounted() {
    this.slideBanner()
  },
  methods: {
    slideBanner() {
      var box = this.$el
      var startPoint = 0
      var stopPoint = 0
      var resetPoint = function () {
        startPoint = 0
        stopPoint = 0
      }
      box.addEventListener('touchstart', (e) => {
        this.autoplay = !this.autoplay
        startPoint = e.changedTouches[0].pageX
      })
      box.addEventListener('touchmove', (e) => {
        // console.log(stopPoint)
        stopPoint = e.changedTouches[0].pageX
      })
      box.addEventListener('touchend', (e) => {
        console.log('end')
        console.log(startPoint - stopPoint)
        if (stopPoint === 0 || startPoint - stopPoint === 0) {
          resetPoint()
          return
        }
        if (startPoint - stopPoint > 0) {
          resetPoint()
          this.$refs.carousel.next()
          return
        }
        if (startPoint - stopPoint < 0) {
          resetPoint()
          this.$refs.carousel.prev()
          return
        }
        this.autoplay = true
      })
    },
  },
}
</script>

<style lang="scss" scoped>
.container {
  padding: 20px;
}
.el-carousel__item h3 {
  color: #475669;
  font-size: 18px;
  opacity: 0.75;
  line-height: 300px;
  text-align: center;
  margin: 0;
}

.el-carousel__item:nth-child(2n) {
  background-color: #99a9bf;
}

.el-carousel__item:nth-child(2n + 1) {
  background-color: #d3dce6;
}
</style>