原生js的轮播图
实现功能:
1.无限自动轮播,鼠标放上去停止轮播,鼠标移开后开始轮播
2.点击左右箭头切换
3.点击小圆点进行切换
<!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: 500px;height: 300px;border: 1px solid #ccc;position: relative;overflow: hidden;}.slide-wrap {width: 100%;height: 100%;position: absolute;left: 0;top: 0;transform: translate(0, 0);display: flex;}.slide {width: 100%;height: 100%;min-width: 500px;justify-content: center;display: flex;align-items: center;}.arrow {width: 30px;height: 30px;position: absolute;top: 50%;translate: translate(0, -50%)}.left {left: 20px;}.right {right: 20px}.indicator {position: absolute;bottom: 20px;left: 50%;width: 60%;transform: translate(-50%, 0);display: flex;justify-content: space-around;}.dot {width: 20px;height: 20px;border-radius: 50%;background: #ccc;}.active {background: red;}</style>
</head><body><!-- 写一个轮播图 --><div class="swiper" id="swiper"><div class="slide-wrap" id="slideWrap"><div class="slide">slide1</div><div class="slide">slide2</div><div class="slide">slide3</div></div><img src="./imgs/left.png" class="arrow left" id="left" /><img src="./imgs/right.png" class="arrow right" id="right" /><div class="indicator"><div class="dot active"></div><div class="dot"></div><div class="dot"></div></div></div><script>const swiper = document.getElementById('swiper');const slideWrap = document.getElementById('slideWrap');const slides = document.getElementsByClassName('slide');const dots = document.getElementsByClassName('dot');const left = document.getElementById('left');const right = document.getElementById('right');let index = 0;const updateDots = () => {Array.from(dots).forEach((item) => {item.classList.remove('active')})dots[index].classList.add('active')}const autoPlay = () => {if (index === slides.length - 1) {index = 0;} else {index++;}slideWrap.style.transform = `translateX(-${index * 500}px)`;updateDots();}let timer = nulltimer = setInterval(autoPlay, 1000)swiper.addEventListener('mouseover', () => {clearInterval(timer)timer = null})swiper.addEventListener('mouseout', () => {timer = setInterval(autoPlay, 1000)})left.addEventListener('click', () => {if (index === 0) {index = slides.length - 1;} else {index--;}slideWrap.style.transform = `translateX(-${index * 500}px)`;updateDots();})right.addEventListener('click', () => {autoPlay()})Array.from(dots).forEach((dot, i) => {dot.addEventListener('click', () => {index = i;slideWrap.style.transform = `translateX(-${index * 500}px)`;updateDots();})})</script></body></html>