参考网址:https://blog.csdn.net/webZRH/article/details/83859905
<template>
<div class="marquee" ref="marqueeRef">
<span class="carousel_arrow carousel_arrow_left" @click="prePage">
<i class="el-icon-arrow-left"></i>
</span>
<span class="carousel_arrow carousel_arrow_right" @click="nextPage">
<i class="el-icon-arrow-right"></i>
</span>
<div
class="marquee_item is-animating"
:style="{
transform: transform,
transition: 'transform ' + transition + 'ms',
}"
>
<div v-for="(carousel, index) in carouselData" :key="index">
<slot name="after" :carousel="carousel"></slot>
</div>
</div>
</div>
</template>
<script>
export default {
name: "marquee", //跑马灯--横向
props: {
carouselData: {
required: true,
type: Array,
default: [],
desc: "轮播数组",
},
autoplay: {
type: Boolean,
default: false,
desc: "是否自动播放",
},
interval: {
type: Number,
default: 3000,
desc: "自动切换的时间间隔,单位为毫秒",
},
direction: {
type: String,
default: "horizontal",
desc: "走马灯展示的方向",
},
},
computed: {
transform() {
return this.direction === "horizontal"
? "translateX(" + this.translateX + "px) scale(1)"
: "translateY(" + this.translateY + "px) scale(1)";
},
},
data() {
return {
index: 0,
transition: 300,
translateX: 0,
translateY: 0,
marqueeWidth: 640,
};
},
mounted() {
this.marqueeWidth = this.$refs.marqueeRef.clientWidth;
console.log(this.marqueeWidth);
this.marquee();
},
methods: {
nextPage() {
if (this.index < this.carouselData.length) {
this.index++;
} else {
this.index = 0;
}
this.marquee();
},
prePage() {
if (this.index > 0) {
this.index--;
} else {
this.index = 0;
}
this.marquee();
let that = this;
if (that.autoplay) {
setTimeout(() => {
that.index++;
that.marquee();
}, that.interval);
}
},
marquee() {
let index = this.index;
console.log(index);
if (index == this.carouselData.length) {
this.index = 0;
this.transition = 0;
this.translateX = 0; // x
this.translateY = 0; // y
} else {
this.transition = 300;
this.translateX = "-" + index * this.marqueeWidth; // x
this.translateY = "-" + index * 40; // y
}
},
},
};
</script>
<style lang="less" scoped>
// 左右滚动
.marquee {
100%;
height: 390px;
overflow: hidden;
position: relative;
}
.marquee_item {
100%;
height: 100%;
background: #fff;
display: block;
margin: 0 auto;
white-space: nowrap;
position: relative;
> div {
display: inline-block;
100%;
height: 100%;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap;
}
}
.carousel_arrow {
height: 36px;
line-height: 36px;
36px;
cursor: pointer;
transition: 0.3s;
border-radius: 50%;
background-color: rgba(31, 45, 61, 0.11);
color: #fff;
position: absolute;
top: 50%;
z-index: 10;
transform: translateY(-50%);
text-align: center;
font-size: 12px;
}
.carousel_arrow_left {
left: 6px;
}
.carousel_arrow_right {
right: 6px;
}
.is-animating {
-webkit-transition: -webkit-transform 0.4s ease-in-out;
transition: -webkit-transform 0.4s ease-in-out;
transition: transform 0.4s ease-in-out;
transition: transform 0.4s ease-in-out, -webkit-transform 0.4s ease-in-out;
}
</style>