jQuery CSS圖片輪播是一種經(jīng)典的網(wǎng)站展示效果,通過JavaScript和CSS技術(shù)的結(jié)合,可以實現(xiàn)多張圖片的切換,使網(wǎng)站頁面更加生動和有趣。
//HTML結(jié)構(gòu) <div class="slider"> <ul class="slider-images"> <li><img src="img1.jpg" alt="image1"></li> <li><img src="img2.jpg" alt="image2"></li> <li><img src="img3.jpg" alt="image3"></li> </ul> <div class="slider-controls"> <button class="prev">上一張</button> <button class="next">下一張</button> </div> </div> //CSS樣式 .slider { position: relative; } .slider ul { list-style: none; margin: 0; padding: 0; } .slider ul li { position: absolute; top: 0; left: 0; opacity: 0; transition: all 0.5s ease-in-out; } .slider ul li.active { opacity: 1; } .slider-controls { position: absolute; bottom: 10px; left: 50%; transform: translateX(-50%); } .slider-controls button { font-size: 16px; padding: 8px 16px; margin: 0 10px; } //JavaScript代碼 $(function() { var $slider = $(".slider"); var $images = $slider.find(".slider-images li"); var $controls = $slider.find(".slider-controls button"); var currentIndex = 0; var nextIndex = 1; $images.eq(0).addClass("active"); $controls.eq(0).click(function() { nextIndex = currentIndex - 1; if (nextIndex< 0) { nextIndex = $images.length - 1; } changeImage(); }); $controls.eq(1).click(function() { nextIndex = currentIndex + 1; if (nextIndex >= $images.length) { nextIndex = 0; } changeImage(); }); function changeImage() { $images.eq(currentIndex).removeClass("active"); $images.eq(nextIndex).addClass("active"); currentIndex = nextIndex; nextIndex++; if (nextIndex >= $images.length) { nextIndex = 0; } } setInterval(changeImage, 3000); });
以上代碼通過jQuery的語法實現(xiàn)了圖片輪播的主要功能:先選中HTML中的元素,然后定義當(dāng)前圖片的索引和下一張圖片的索引,通過點擊上一張和下一張按鈕來改變索引值并實現(xiàn)圖片的切換效果,最后采用setInterval函數(shù)來定時觸發(fā)圖片的自動切換。同時,在CSS代碼中,通過absolute布局和transition過渡效果來實現(xiàn)圖片的平滑切換過程。