常见Web组件的实现
如何实现轮播图 Slideshow
要让幻灯片自动切换,可以通过定时器来实现
源代码:
点击运行 »
<!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <style> * { box-sizing: border-box } body { font-family: Verdana, sans-serif; } .mySlides { display: none } /* 轮播图容器 */ .slideshow-container { max-width: 1000px; position: relative; margin: auto; } /* 上一张和下一张的按钮 */ .prev, .next { cursor: pointer; position: absolute; top: 50%; width: auto; padding: 16px; margin-top: -22px; color: white; font-weight: bold; font-size: 18px; transition: 0.6s ease; border-radius: 0 3px 3px 0; } /* 将”下一张“的按钮定位在右边 */ .next { right: 0; border-radius: 3px 0 0 3px; } /* 鼠标移到按钮上,增加一个有点透明的黑色背景 */ .prev:hover, .next:hover { background-color: rgba(0, 0, 0, 0.8); } /* 标题的文本 */ .text { color: #f2f2f2; font-size: 15px; padding: 8px 12px; position: absolute; bottom: 8px; width: 100%; text-align: center; } /* 图片顺序的文本,(如,1/3) */ .numbertext { color: #f2f2f2; font-size: 12px; padding: 8px 12px; position: absolute; top: 0; } /* 底部的指示按钮 */ .dot { cursor: pointer; height: 13px; width: 13px; margin: 0 2px; background-color: #bbb; border-radius: 50%; display: inline-block; transition: background-color 0.6s ease; } .active, .dot:hover { background-color: #717171; } /* 淡入淡出的动画 */ .fade { -webkit-animation-name: fade; -webkit-animation-duration: 1.5s; animation-name: fade; animation-duration: 1.5s; } @-webkit-keyframes fade { from { opacity: .4 } to { opacity: 1 } } @keyframes fade { from { opacity: .4 } to { opacity: 1 } } </style> </head> <body> <h2>轮播图自动切换</h2> <p>每两秒更改到下一张图片:</p> <div class="slideshow-container"> <div class="mySlides fade"> <div class="numbertext">1 / 3</div> <img src="https://image-10001577.image.myqcloud.com/upload/3/20170428/14933734123710.jpg" style="width:100%"> <div class="text">标题1</div> </div> <div class="mySlides fade"> <div class="numbertext">2 / 3</div> <img src="https://image-10001577.image.myqcloud.com/upload/3/20170428/1493373435281.jpg" style="width:100%"> <div class="text">标题2</div> </div> <div class="mySlides fade"> <div class="numbertext">3 / 3</div> <img src="https://image-10001577.image.myqcloud.com/upload/3/20170428/14933734551830.jpg" style="width:100%"> <div class="text">标题3</div> </div> </div> <br> <div style="text-align:center"> <span class="dot"></span> <span class="dot"></span> <span class="dot"></span> </div> <script> var slideIndex = 0; showSlides(); function showSlides() { var i; var slides = document.getElementsByClassName("mySlides"); var dots = document.getElementsByClassName("dot"); for (i = 0; i < slides.length; i++) { slides[i].style.display = "none"; } slideIndex++; if (slideIndex > slides.length) { slideIndex = 1 } for (i = 0; i < dots.length; i++) { dots[i].className = dots[i].className.replace(" active", ""); } slides[slideIndex - 1].style.display = "block"; dots[slideIndex - 1].className += " active"; // 每两秒展示下一张图片 setTimeout(showSlides, 2000); } </script> </body> </html>
运行结果:
点击运行 »