HTML5切換焦點(diǎn)圖是現(xiàn)在網(wǎng)頁設(shè)計(jì)中常見的一種交互方式。它可以讓頁面變得更加生動(dòng)和有趣。下面我們介紹一種使用HTML5和CSS3實(shí)現(xiàn)的切換焦點(diǎn)圖的代碼。
<!DOCTYPE html> <html> <head> <meta charset="UTF-8"> <title>切換焦點(diǎn)圖</title> <style> .container { width: 800px; height: 400px; position: relative; } .container img { width: 800px; height: 400px; position: absolute; top: 0; left: 0; opacity: 0; transition: all 0.5s; } .container img.active { opacity: 1; } .nav { width: 100%; height: 50px; position: absolute; bottom: 0; display: flex; justify-content: center; align-items: center; } .nav span { width: 10px; height: 10px; border-radius: 50%; background-color: gray; margin: 0 10px; cursor: pointer; transition: all 0.5s; } .nav span.active { background-color: white; } </style> </head> <body> <div class="container"> <img src="image1.jpg" class="active"> <img src="image2.jpg"> <img src="image3.jpg"> <img src="image4.jpg"> <div class="nav"> <span class="active"></span> <span></span> <span></span> <span></span> </div> </div> <script> // 獲取元素 var container = document.querySelector('.container'); var images = container.querySelectorAll('img'); var nav = container.querySelector('.nav'); var spans = nav.querySelectorAll('span'); // 初始值 var currentIndex = 0; var timer; // 自動(dòng)播放 function autoPlay() { timer = setInterval(function() { var lastIndex = currentIndex; currentIndex++; if (currentIndex >= images.length) { currentIndex = 0; } images[lastIndex].classList.remove('active'); images[currentIndex].classList.add('active'); spans[lastIndex].classList.remove('active'); spans[currentIndex].classList.add('active'); }, 2000); } autoPlay(); // 點(diǎn)擊小圓點(diǎn)切換圖片 nav.addEventListener('click', function(e) { if (e.target.tagName === 'SPAN') { clearInterval(timer); var lastIndex = currentIndex; currentIndex = Array.prototype.indexOf.call(spans, e.target); images[lastIndex].classList.remove('active'); images[currentIndex].classList.add('active'); spans[lastIndex].classList.remove('active'); spans[currentIndex].classList.add('active'); autoPlay(); } }); </script> </body> </html>
以上就是一個(gè)簡單的使用HTML5和CSS3實(shí)現(xiàn)的切換焦點(diǎn)圖的代碼。可以看到,我們使用了flex布局和transition動(dòng)畫來實(shí)現(xiàn)圖像和小圓點(diǎn)的切換效果。
上一篇html5列表展開代碼
下一篇mysql中怎么倒序查詢