CSS手動(dòng)輪播圖是一種簡(jiǎn)單但實(shí)用的網(wǎng)頁(yè)設(shè)計(jì)元素,它能夠在網(wǎng)頁(yè)中創(chuàng)建動(dòng)態(tài)、引人注目的圖片輪播效果。為了實(shí)現(xiàn)這種效果,我們需要使用一些CSS代碼來(lái)定義輪播圖的樣式,并且還需要一些JavaScript代碼來(lái)控制輪播過(guò)程。下面是一個(gè)示例CSS手動(dòng)輪播圖的代碼。
<html> <head> <style> h1 { text-align: center; font-size: 30px; color: #007acc; margin-top: 30px; } .wrapper { width: 500px; height: 300px; margin: 50px auto; position: relative; overflow: hidden; } .wrapper img { width: 500px; height: 300px; position: absolute; top: 0; left: 0; opacity: 0; transition: all 1s ease-in-out; } .wrapper img.active { opacity: 1; z-index: 1; } .wrapper img.next { opacity: 1; z-index: 2; transform: translateX(100%); } .wrapper .arrow { width: 50px; height: 50px; background-color: #007acc; position: absolute; top: 50%; transform: translateY(-50%); cursor: pointer; z-index: 3; } .wrapper .arrow.left { left: 10px; } .wrapper .arrow.right { right: 10px; } </style> </head> <body> <h1>CSS手動(dòng)輪播圖</h1> <div class="wrapper"> <div class="arrow left"></div> <div class="arrow right"></div> </div> <script> const images = document.querySelectorAll('.wrapper img'); const leftArrow = document.querySelector('.arrow.left'); const rightArrow = document.querySelector('.arrow.right'); let current = 0; function reset() { for (let i = 0; i < images.length; i++) { images[i].classList.remove('active'); images[i].classList.remove('next'); } } function slideLeft() { reset(); images[current].classList.add('next'); current = (current == 0) ? images.length - 1 : current - 1; images[current].classList.add('active'); } function slideRight() { reset(); images[current].classList.add('next'); current = (current == images.length - 1) ? 0 : current + 1; images[current].classList.add('active'); } leftArrow.addEventListener('click', slideLeft); rightArrow.addEventListener('click', slideRight); </script> </body> </html>
上面的代碼中,我們定義了一個(gè)包含三張圖片的輪播圖,以及兩個(gè)箭頭元素用于左右切換。CSS部分定義了輪播圖容器的大小、位置、背景、圖片樣式、箭頭樣式等。JavaScript部分實(shí)現(xiàn)了箭頭點(diǎn)擊事件,通過(guò)改變當(dāng)前激活圖片的類(lèi)名來(lái)實(shí)現(xiàn)圖片的輪播效果。