現(xiàn)在網(wǎng)絡(luò)上的許多網(wǎng)站都采用了輪播圖,這樣可以使頁面更加美觀,同時(shí)還可以在一定程度上提升用戶體驗(yàn)。下面我們就看一下如何使用 HTML 實(shí)現(xiàn)一個(gè)左右輪播圖。
<html> <head> <style> #carousel { width: 500px; overflow: hidden; position: relative; margin: 0 auto; } #carousel img { float: left; margin: 0; padding: 0; width: 500px; position: relative; } #carousel .slides { display: block; width: 5000px; position: relative; left: 0; animation: slide 10s infinite; } @keyframes slide { 0% { left: 0; } 25% { left: -1000px; } 50% { left: -2000px; } 75% { left: -3000px; } 100% { left: 0; } } .controls { width: 500px; margin: 0 auto; } .controls span { cursor: pointer; display: inline-block; width: 15px; height: 15px; background-color: #ccc; margin-right: 5px; border-radius: 50%; } .controls .active { background-color: #333; } </style> </head> <body> <div id="carousel"> <div class="slides"> <img src="img1.jpg" alt="image1"> <img src="img2.jpg" alt="image2"> <img src="img3.jpg" alt="image3"> <img src="img4.jpg" alt="image4"> <img src="img5.jpg" alt="image5"> </div> <div class="controls"> <span id="1" class="active"></span> <span id="2"></span> <span id="3"></span> <span id="4"></span> <span id="5"></span> </div> </div> <script> var controls = document.querySelectorAll(".controls span"); var slides = document.querySelector(".slides"); for (var i = 0; i < controls.length; i++) { controls[i].onclick = function () { var id = this.getAttribute("id"); document.querySelector(".controls .active").classList.remove("active"); this.classList.add("active"); slides.style.left = -((id - 1) * 1000) + "px"; } } setInterval(function () { var active = document.querySelector(".controls .active"); var next = active.nextElementSibling; if (!next) { next = document.querySelector(".controls span:first-child"); } active.classList.remove("active"); next.classList.add("active"); slides.style.left = -(parseInt(next.getAttribute("id")) - 1) * 1000 + "px"; }, 5000); </script> </body> </html>
以上就是一個(gè) HTML 實(shí)現(xiàn)的左右輪播圖的代碼。其中,我們使用了 CSS 中的 animation 屬性來實(shí)現(xiàn)圖片的滑動(dòng),同時(shí)還加上了控制條,讓用戶可以手動(dòng)控制圖片的輪播。JS 中的 setInterval 則是用來定時(shí)自動(dòng)播放圖片。