圖片輪播效果可以使網(wǎng)頁看起來更加生動(dòng)有趣,HTML實(shí)現(xiàn)圖片輪播效果的代碼如下:
<html> <head> <title>圖片輪播</title> <style> .slider { overflow: hidden; width: 600px; height: 400px; } .slider img { width: 600px; height: 400px; float: left; } </style> </head> <body> <div class="slider"> <img src="slide1.jpg"> <img src="slide2.jpg"> <img src="slide3.jpg"> </div> <script> var slider = document.querySelector(".slider"); var imgs = slider.getElementsByTagName("img"); var current = 1; setInterval(function() { if (current < imgs.length - 1) { current++; slider.style.transform = "translateX(-" + current * 600 + "px)"; } else { current = 1; slider.style.transform = "translateX(0)"; } }, 3000); </script> </body> </html>
上述代碼中,div元素.slider用來包含圖片,img標(biāo)簽是要輪播的圖片,script標(biāo)簽用來實(shí)現(xiàn)輪播功能。具體實(shí)現(xiàn)方法是通過定時(shí)器setInterval,每3秒切換下一張圖片,切換圖片時(shí)改變div元素的transform屬性來實(shí)現(xiàn)動(dòng)畫效果。