先看效果:
![](https://i-blog.csdnimg.cn/blog_migrate/c63195a0706ed54d0ed0f2c7d4835a16.png)
html 代码:
<div class="showImg">
<!-- //轮播图片 -->
<img
class="img"
@mouseover="changeInterval(true)"
@mouseleave="changeInterval(false)"
v-for="item in imgArr"
:key="item.id"
:src="item.url"
alt="暂无图片"
v-show="item.id === currentIndex"
/>
<!-- //左侧按钮 -->
<div @click="clickIcon('up')" class="iconDiv icon-left">
<i class="el-icon-caret-left"></i>
</div>
<!-- //右侧按钮 -->
<div @click="clickIcon('down')" class="iconDiv icon-right">
<i class="el-icon-caret-right"></i>
</div>
<!-- //控制圆点 -->
<div class="banner-circle">
<ul class="banner-ul">
<li
class="banner-li"
@click="changeImg(item.id)"
v-for="item in imgArr"
:key="item.id"
>
<div v-if="item.id === currentIndex" class="element1">
<div class="child1"></div>
</div>
</li>
</ul>
</div>
</div>
js代码:
data() {
return {
currentIndex: 0, //当前所在图片下标
timer: null, //定时轮询
imgArr: [
{ id: 0, url: require("../../../../assets/img/car0.png") },
{
id: 1,
url: require("../../../../assets/img/car1.png"),
},
{
id: 2,
url: require("../../../../assets/img/car2.png"),
},
{
id: 3,
url: require("../../../../assets/img/car3.png"),
},
],
};
},
mounted() {
this.startInterval();
},
methods: {
//开启定时器
startInterval() {
// 事件里定时器应该先清除在设置,防止多次点击直接生成多个定时器
clearInterval(this.timer);
this.timer = setInterval(() => {
this.currentIndex++;
if (this.currentIndex > this.imgArr.length - 1) {
this.currentIndex = 0;
}
}, 3000);
},
// 点击左右箭头
clickIcon(val) {
if (val === "down") {
this.currentIndex++;
if (this.currentIndex === this.imgArr.length) {
this.currentIndex = 0;
}
} else {
if (this.currentIndex === 0) {
this.currentIndex = this.imgArr.length;
}
this.currentIndex--;
}
},
// 点击控制圆点
changeImg(index) {
this.currentIndex = index;
},
//鼠标移入移出控制
changeInterval(val) {
if (val) {
clearInterval(this.timer);
} else {
this.startInterval();
}
},
}
css代码:
<style scoped lang="scss">
.showImg {
position: relative;
margin:0 auto;
padding: 30px;
/* 轮播图片 */
.img {
width: 356px;
height: 440px;
}
/* 箭头图标 */
.iconDiv {
position: absolute;
top: 50%;
transform: translateY(-50%);
width: 30px;
height: 30px;
border: 1px solid #666;
border-radius: 15px;
background-color: rgba(125, 125, 125, 0.2);
line-height: 30px;
text-align: center;
font-size: 25px;
cursor: pointer;
}
.iconDiv:hover {
background-color: white;
}
.icon-left {
left: 40px;
}
.icon-right {
right: 40px;
}
/* 控制圆点 */
.banner-circle {
margin-top: -60px;
.banner-ul {
display: flex;
justify-content: center;
.banner-li {
width: 16px;
height: 16px;
margin-right: 30px;
background: #fff;
border-radius: 50%;
list-style-type: none;
&:hover{
border: 1px solid #118a84;
cursor:pointer;
}
.element1 {
width: 16px;
height: 16px;
background: #fff;
border-radius: 50%;
border: 1px solid #118a84;
.child1 {
width: 8px;
height: 8px;
border-radius: 50%;
background-color: #118a84;
position: relative;
transform: translate(40%, 35%);
// top: 3px;
// left: 3px;
}
}
}
}
}
}
</style>