走马灯实现

原文地址:在vue中使用 element的carousel走马灯组件、用键盘左右按键控制轮播切换 - 简书

<template>
  <div>
    {{carouselIndex}}
    <el-carousel :autoplay='true' :interval="2000" arrow="always"  type="card" height="200px"  ref="carouselRef">
      <el-carousel-item v-for="item in listArr" :key="item.index">
        <img :src="item.url" alt="">
      </el-carousel-item>
    </el-carousel>
  </div>
</template>

<script>
export default {
  data(){
    return{
      carouselIndex:0,
      listArr:[
        {
          index:0,
          url:''
        },
        {
          index:1,
          url:''
        },
        {
          index:2,
          url:''
        },
      ]
    }
  },
  methods:{
    // 上一页
    prevFun(){
      if(this.carouselIndex == 0){
        this.carouselIndex  = this.listArr.length-1
      }else{
        this.carouselIndex --
      }
      this.$refs.carouselRef.setActiveItem(this.carouselIndex)
    },
    // 下一页
    nextFun(){
      if(this.carouselIndex < this.listArr.length-1){
        this.carouselIndex ++ 
      }else{
        this.carouselIndex = 0
      }
      this.$refs.carouselRef.setActiveItem(this.carouselIndex)
    },
    keyDown() {
      document.onkeydown =  (e) => {
        //事件对象兼容
        let e1 = e || event || window.event || arguments.callee.caller.arguments[0]
        //键盘按键判断:左箭头-37;上箭头-38;右箭头-39;下箭头-40
        //左
        if (e1 && e1.keyCode == 37) {
          this.prevFun()
          // 按下左箭头
        } else if (e1 && e1.keyCode == 39) {
          this.nextFun()
          // 按下右箭头
        }
      }
    },
  },
  mounted(){
    this.keyDown()
  }
}
</script>

<style>
 .el-carousel__item h3 {
    color: #475669;
    font-size: 14px;
    opacity: 0.75;
    line-height: 200px;
    margin: 0;
  }
  
  .el-carousel__item:nth-child(2n) {
    background-color: #99a9bf;
  }
  
  .el-carousel__item:nth-child(2n+1) {
    background-color: #d3dce6;
  }
</style>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值