在学习js时写的轮播图实例,效果为平移轮播
通过设置定时器和监听鼠标事件来控制图片的切换
使用 CSS 过渡效果和偏移量来实现平滑的切换动画效果
根据当前显示的图片索引来改变对应的圆点背景颜色。
<!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1"> <title></title> <style> .banner{ width: 100%; height: 300px; overflow: hidden; } .list{ width: 400%; height: 300px; display: flex; } .list img{ width: 25%; height: 300px; } .box{ width: 100%; height: 300px; position: relative; } .but{ width: 100%; height: 50px; position: absolute; top: 125px; display: flex; justify-content: space-between; } .but div{ width: 50px; height: 50px; background-color: rgba(0, 0, 0, 0.5); color: #fff; line-height: 50px; text-align: center; font-size: 20px; } .iocn{ width: 100%; height: 30px; position: absolute; bottom: 0; display: flex; justify-content: center; } .iocn span{ display: block; width: 10px; height: 10px; margin: 10px; border-radius: 100%; background-color: rgba(0,0,0,0.5); } </style> </head> <body> <div class="box"> <div class="banner"> <div class="list"> <img src="img/1.jpg" alt=""> <img src="img/11.JPG" alt=""> <img src="img/111.JPG" alt=""> <img src="img/1111.jpg" alt=""> </div> </div> <div class="but"> <div> < </div> <div> > </div> </div> <div class="iocn"> <span style="background-color: rgba(255,0,0,0.5);"></span> <span></span> <span></span> </div> </div> <script> let box = document.getElementsByClassName('box')[0]; let list = document.getElementsByClassName("list")[0]; let img = list.children; let imgWidth = img[0].offsetWidth; let k = 0; let int = setInterval(scroll,2000); let iocn = document.getElementsByClassName('iocn')[0].children; let but = document.getElementsByClassName('but')[0].children; function scroll(){ for(let i = 0; i < iocn.length; i++){ iocn[i].style.backgroundColor = "rgba(0, 0, 0, 0.5)" } k++; list.style.transition = "all 1s"; list.style.marginLeft = "-" + k * imgWidth + "px"; if(k == img.length - 1){ iocn[0].style.backgroundColor = "rgba(255, 0, 0, 0.5)" setTimeout(function(){ k = 0; list.style.transition = ""; list.style.marginLeft = "0px"; },1000) }else{ iocn[k].style.backgroundColor = "rgba(255, 0, 0, 0.5)" } } box.onmouseover = function(){ clearInterval(int); } box.onmouseout = function(){ int = setInterval(scroll,2000); } but[0].onclick = function(){ for(let i = 0; i < iocn.length; i++){ iocn[i].style.backgroundColor = "rgba(0, 0, 0, 0.5)" } if(k == 0){ k = img.length-1; list.style.transition = ""; list.style.marginLeft = "-" + k * imgWidth + "px"; iocn[img.length-2].style.backgroundColor = "rgba(255, 0, 0, 0.5)" } setTimeout(function(){ k--; list.style.transition = "all 1s"; iocn[k].style.backgroundColor = "rgba(255, 0, 0, 0.5)" list.style.marginLeft = "-" + k * imgWidth + "px"; },100) } but[1].onclick = scroll; </script> </body> </html>