实现效果:
HTML部分
html
<div class="carousel">
<div class="carousel-wrapper">
<img src="./image/1.png" alt="">
</div>
<ul class="carousel-indictor">
<li class="active" data-id="0"></li>
<li data-id="1"></li>
<li data-id="2"></li>
<li data-id="3"></li>
</ul>
<div class="toggle">
<button class="prev"><</button>
<button class="next">></button>
</div>
</div>
CSS部分
css
<style>
*{
margin: 0;
padding: 0;
box-sizing: border-box;
}
li{
list-style: none;
}
button{
border: none;
outline: none;
}
.carousel{
position: relative;
width: 700px;
height: 300px;
margin: 50px auto;
}
.carousel-wrapper{
width: 700px;
height: 300px;
}
.carousel-wrapper img{
width: 100%;
height: 100%;
}
.carousel-indictor{
position: absolute;
bottom: 30px;
left: 150px;
width: 400px;
height: 5px;
display: flex;
justify-content: space-between;
}
.carousel-indictor li{
width: 85px;
background-color: rgba(235, 239, 243);
}
.carousel-indictor li.active{
background-color: #fff;
}
.toggle button{
display: none;
width: 50px;
height: 50px;
background-color: rgba(191, 201, 212,0.5);
border-radius: 50%;
color: #fff;
font-size: 25px;
}
.carousel:hover .toggle button{
display: block;
}
.toggle button:hover{
background-color: rgb(125, 140, 161);
cursor: pointer;
}
.toggle .prev{
top: 125px;
left: 30px;
position: absolute;
}
.toggle .next{
top: 125px;
right: 30px;
position: absolute;
}
</style>
JS部分
javascript
<script>
const data = [
{url:'./image/1.png'},
{url:'./image/2.png'},
{url:'./image/3.png'},
{url:'./image/4.png'}
]
const img = document.querySelector('.carousel-wrapper img')
// 1.右键
const next = document.querySelector('.next')
let i = 0
next.addEventListener('click',function(){
// console.log(data[i]);
i++
i = i>3 ? 0 : i
img.src=data[i].url
document.querySelector('.carousel-indictor .active').classList.remove('active')
document.querySelector(`.carousel-indictor li:nth-child(${i+1})`).classList.add('active')
})
// 2.左键
const prev = document.querySelector('.prev')
prev.addEventListener('click',function(){
i--
i = i<0 ? i=3 : i
// 图像
img.src=data[i].url
// 下划线
document.querySelector('.carousel-indictor .active').classList.remove('active')
document.querySelector(`.carousel-indictor li:nth-child(${i+1})`).classList.add('active')
})
// 3.定时器
let timerId = setInterval(function(){
next.click()
},1000)
const carousel = document.querySelector('.carousel')
carousel.addEventListener('mouseenter',function(){
clearInterval(timerId)
})
carousel.addEventListener('mouseleave',function(){
timerId= setInterval(function(){
next.click()
},1000)
})
// 4.经过li时,也对应跳转
const ul = document.querySelector('.carousel-indictor')
ul.addEventListener('click',function(e){
if(e.target.tagName === 'LI'){
document.querySelector('.carousel-indictor .active').classList.remove('active')
e.target.classList.add('active')
// console.log(e.target.dataset.id);
const i = e.target.dataset.id
img.src=data[e.target.dataset.id].url
}
})
</script>