在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>
image.png
最后編輯于
?著作權歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務。

友情鏈接更多精彩內(nèi)容