vue实现一个定时无缝滚动的轮播图并且左右有按钮能控制左右滑动鼠标悬停会停止滚动 鼠标移开 能继续滚动并且下面带有圆点 也能控制图片的选中和展示
以下是一个基于Vue实现的定时无缝滚动的轮播图的示例代码:
<template>
<div class="carousel">
<div class="carousel-container" :style="{ transform: 'translateX(' + (-currentIndex * 100) + '%)' }">
<div class="carousel-item" v-for="(item, index) in items" :key="index">
<img :src="item.imgSrc" alt="">
</div>
</div>
<div class="carousel-controls">
<button class="carousel-control" @click="prev"><i class="fas fa-chevron-left"></i></button>
<button class="carousel-control" @click="next"><i class="fas fa-chevron-right"></i></button>
</div>
<div class="carousel-dots">
<span class="carousel-dot" v-for="(item, index) in items" :key="index" :class="{ 'active': index === currentIndex }" @click="goTo(index)"></span>
</div>
</div>
</template>
<script>
export default {
data() {
return {
items: [
{ imgSrc: 'https://picsum.photos/id/237/300/200' },
{ imgSrc: 'https://picsum.photos/id/238/300/200' },
{ imgSrc: 'https://picsum.photos/id/239/300/200' },
{ imgSrc: 'https://picsum.photos/id/240/300/200' }
],
currentIndex: 0,
timer: null
}
},
mounted() {
this.startTimer()
},
methods: {
startTimer() {
this.timer = setInterval(() => {
this.next()
}, 3000)
},
resetTimer() {
clearInterval(this.timer)
this.startTimer()
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length
this.resetTimer()
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length
this.resetTimer()
},
goTo(index) {
this.currentIndex = index
this.resetTimer()
}
}
}
</script>
<style scoped>
.carousel {
position: relative;
overflow: hidden;
width: 100%;
height: 400px;
}
.carousel-container {
display: flex;
transition: transform 0.5s;
}
.carousel-item {
flex-shrink: 0;
width: 100%;
}
.carousel-item img {
width: 100%;
height: 100%;
object-fit: cover;
}
.carousel-controls {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 100%;
display: flex;
justify-content: space-between;
z-index: 1;
}
.carousel-control {
background-color: rgba(0, 0, 0, 0.5);
color: #fff;
border: none;
font-size: 24px;
padding: 10px 15px;
cursor: pointer;
transition: background-color 0.2s;
}
.carousel-control:hover {
background-color: rgba(0, 0, 0, 0.7);
}
.carousel-dots {
position: absolute;
bottom: 10px;
left: 50%;
transform: translateX(-50%);
display: flex;
}
.carousel-dot {
width: 10px;
height: 10px;
border-radius: 50%;
background-color: rgba(0, 0, 0, 0.5);
margin-right: 10px;
cursor: pointer;
transition: background-color 0.2s;
}
.carousel-dot:last-child {
margin-right: 0;
}
.carousel-dot.active {
background-color: #fff;
}
</style>
该轮播图组件有以下特点:
- 使用了flex布局实现图片的水平排列
- 使用了transform属性实现图片的滚动效果
- 使用了setInterval函数实现定时滚动
- 使用了clearInterval函数实现滚动停止
- 使用了按钮和圆点实现用户控制图片的滚动
通过以上实现,我们就可以得到一个基于Vue的定时无缝滚动的轮播图,并且具备用户控制和交互的功能。
原文地址: https://www.cveoy.top/t/topic/btJl 著作权归作者所有。请勿转载和采集!