<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