<div id="slider"> <img src="img1.jpg"> <img src="img2.jpg"> <img src="img3.jpg"> <img src="img4.jpg"> <img src="img5.jpg"> <button id="prevBtn">上一张</button> <button id="nextBtn">下一张</button> </div>
#slider { width: 500px; height: 300px; overflow: hidden; } #slider img { width: 100%; height: 100%; } #prevBtn, #nextBtn { background-color: #000; color: #fff; padding: 10px 20px; border: none; cursor: pointer; position: absolute; top: 50%; transform: translateY(-50%); } #prevBtn { left: 0; } #nextBtn { right: 0; }
var slider = document.getElementById('slider'); var prevBtn = document.getElementById('prevBtn'); var nextBtn = document.getElementById('nextBtn'); var images = slider.getElementsByTagName('img'); var currentIndex = 0; function showImage(index) { for (var i = 0; i < images.length; i++) { images[i].style.display = 'none'; } images[index].style.display = 'block'; } prevBtn.addEventListener('click', function() { currentIndex = (currentIndex - 1 + images.length) % images.length; showImage(currentIndex); }); nextBtn.addEventListener('click', function() { currentIndex = (currentIndex + 1) % images.length; showImage(currentIndex); }); setInterval(function() { currentIndex = (currentIndex + 1) % images.length; showImage(currentIndex); }, 3000);
本文为翻滚的胖子原创文章,转载无需和我联系,但请注明来自猿教程iskeys.com