Vue 实现定时无缝滚动轮播图 - 带按钮、圆点控制及鼠标悬停停止
<template>
<div class='carousel' @mouseover='stopTimer' @mouseout='startTimer'>
<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)
},
stopTimer() {
clearInterval(this.timer)
},
prev() {
this.currentIndex = (this.currentIndex - 1 + this.items.length) % this.items.length
this.startTimer()
},
next() {
this.currentIndex = (this.currentIndex + 1) % this.items.length
this.startTimer()
},
goTo(index) {
this.currentIndex = index
this.startTimer()
}
}
}
</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>
<p>该轮播图组件使用 Vue 实现,具备以下特点:</p>
<ul>
<li>使用 flex 布局实现图片水平排列</li>
<li>使用 transform 属性实现图片滚动效果</li>
<li>使用 setInterval 函数实现定时滚动</li>
<li>使用 clearInterval 函数实现滚动停止</li>
<li>使用 左右按钮 和 底部圆点 实现用户控制图片的滚动</li>
<li>鼠标悬停在轮播图上时,滚动会停止,鼠标移开后继续滚动</li>
</ul>
<p>通过以上实现,我们就可以得到一个基于 Vue 的定时无缝滚动的轮播图,并具备用户控制和交互的功能。</p>
原文地址: https://www.cveoy.top/t/topic/mXfK 著作权归作者所有。请勿转载和采集!