html + css + js 实现简易轮播图
code
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
.swiper {
width: 200px;
height: 100px;
background-color: #e1e1e1;
position: relative;
overflow: hidden;
}
.swiper-item {
width: 100%;
height: 100%;
text-align: center;
line-height: 100px;
display: inline-block;
position: absolute;
display: none;
}
.swiper-item:nth-child(1) {
background-color: pink;
}
.swiper-item:nth-child(2) {
background-color: skyblue;
}
.swiper-item:nth-child(3) {
background-color: silver;
}
.swiper-item:nth-child(4) {
background-color: rgb(255, 251, 192);
}
.active-enter {
animation-name: enterSwiper;
animation-duration: 1s;
animation-fill-mode: forwards;
}
.active-leave {
animation-name: leaveSwiper;
animation-duration: 1s;
animation-fill-mode: forwards;
}
@keyframes enterSwiper {
0% {
transform: translateX(100%);
}
100% {
transform: translateX(0);
}
}
@keyframes leaveSwiper {
0% {
transform: translateX(0);
}
100% {
transform: translateX(-100%);
}
}
</style>
</head>
<body>
// 轮播图区域
<div class="swiper">
<div class="swiper-item" data-index="1">1</div>
<div class="swiper-item" data-index="2">2</div>
<div class="swiper-item" data-index="3">3</div>
<div class="swiper-item" data-index="4">4</div>
</div>
<script>
const swiperList = document.querySelector('.swiper')
const swiper = document.querySelectorAll('.swiper-item');
let timer = null;
let index = 2;
swiper[0].style.display = 'block'
swiper[0].classList.add('active-enter')
function swiperFn () {
swiper.forEach((item, i) => {
if(index === i + 1) {
item.style.display = 'block'
if(item.classList.contains('active-leave')) {
item.classList.replace('active-leave', 'active-enter')
} else {
item.classList.add('active-enter')
}
} else {
setTimeout(() => {
item.style.display = 'none'
if(item.classList.contains('active-leave')) {
item.classList.remove('active-leave')
}
}, 1000)
if(item.classList.contains('active-enter')) {
item.classList.replace('active-enter', 'active-leave')
}
}
})
index += 1
if(index > swiper.length) {
index = 1
}
}
timer = setInterval(() => {
swiperFn()
}, 3000)
swiperList.addEventListener('mouseenter', () => {
clearInterval(timer)
})
swiperList.addEventListener('mouseleave', () => {
timer = setInterval(() => {
swiperFn()
}, 3000)
})
</script>
</body>
</html>