Element-ui 走马灯增加移动端左右触摸滑屏效果

349 阅读1分钟
<template>
  <section class="demo-container">
    <h1>Carousel - 走马灯</h1>
    <el-carousel v-model="value" ref="carouse" :autoplay="autoplay" class="carousel-wrap">
      <el-carousel-item>
        <div class="demo-carousel">1</div>
      </el-carousel-item>
      <el-carousel-item>
        <div class="demo-carousel">2</div>
      </el-carousel-item>
      <el-carousel-item>
        <div class="demo-carousel">3</div>
      </el-carousel-item>
      <el-carousel-item>
        <div class="demo-carousel">4</div>
      </el-carousel-item>
    </el-carousel>
  </section>
</template>

<script lang="ts">
import Vue from 'vue'
export default Vue.extend({
  name: 'HomeIndex',
  data() {
    return {
      value: 0,
      autoplay: true,
    }
  },
  mounted() {
    this.slideBanner()
  },
  methods: {
    slideBanner() {
      const box = document.querySelector('.carousel-wrap') as Element
      const that: any = this
      let startPoint = 0
      let stopPoint = 0

      const resetPoint = () => {
        startPoint = 0
        stopPoint = 0
      }

      // 手指按下
      box.addEventListener('touchstart', (e: any) => {
        that.autoplay = false
        // 记录起始坐标值
        startPoint = e.changedTouches[0].pageX
      })

      // 手指滑动
      box.addEventListener('touchmove', (e: any) => {
        // 记录结束坐标这
        stopPoint = e.changedTouches[0].pageX
      })

      // 手指抬起,判断向左还是向右滚动
      box.addEventListener('touchend', () => {
        // 手指抬起开始自动播放
        that.autoplay = true

        // 不移动
        if (stopPoint === 0 || startPoint - stopPoint === 0) {
          resetPoint()
          return
        }

        // 向右移动
        if (startPoint - stopPoint > 0) {
          resetPoint()
          that.$refs.carouse.next()
          return
        }

        // 向左移动
        if (startPoint - stopPoint < 0) {
          resetPoint()
          that.$refs.carouse.prev()
          return
        }
      })
    },
  },
})
</script>

<style lang="scss">
.demo-container {
  h1 {
    text-align: center;
    height: 100px;
    line-height: 80px;
  }
  .carousel-wrap {
    height: 400px;
  }
  .demo-carousel {
    height: 400px;
    line-height: 400px;
    width: 100%;
    text-align: center;
    font-size: 30px;
    color: #fff;
  }
  .el-carousel__item {
    &:nth-of-type(1) .demo-carousel {
      background: #79e4f8;
    }
    &:nth-of-type(2) .demo-carousel {
      background: #a14ae6;
    }
    &:nth-of-type(3) .demo-carousel {
      background: #ff8c11;
    }
    &:nth-of-type(4) .demo-carousel {
      background: #fe0e11;
    }
  }
}
</style>