纯js实现淘宝商城轮播图
需求:
循环无缝自动轮播3张图片,点击左右箭头可以手动切换图片,鼠标点击轮播图下面的小圆点会跳转到对应的第几张图片。鼠标放到轮播图的图片上时不再自动轮播,鼠标移开之后又继续轮播。
效果图:
下面是html代码:
<div id="box"> <div id="imgbox"> <div><img src="img/tu1.jpg" alt="" /></div> <div><img src="img/tu2.jpg" alt="" /></div> <div><img src="img/tu3.jpg" alt="" /></div> </div> <div class="yuandian"> <a href="#" class="xiaoyuan"></a> <a href="#" class="xiaoyuan"></a> <a href="#" class="xiaoyuan"></a> </div> <div id="jiantou"> <span id="jt_left" class="jiant"><</span> <span id="jt_right" class="jiant">></span> </div> </div>
css代码:
* { margin: 0; padding: 0; } #box { position: relative; width: 520px; height: 280px; /*background-color: pink;*/ margin:100px auto; overflow: hidden; } #imgbox { position: absolute; top: 0; left: 0; width: 99999px; cursor: pointer; height: 100%; } #imgbox img { float: left; } .yuandian { position: absolute; left: 230px; bottom: 20px; width: 60px; height: 15px; border-radius: 20px; background: rgba(255,255,255,.6); } .yuandian a { float: left; width: 10px; height: 10px; border-radius: 10px; margin: 2px 0 0 7px; background-color: white; } #jt_left { left: 0; border-top-right-radius:2em; border-bottom-right-radius:2em; } #jt_left, #jt_right { position: absolute; top: 140px; width: 35px; height: 35px; line-height: 35px; cursor: pointer; font-size: 18px; text-align: center; background: rgba(255,255,255,.6); } #jt_right { right: 0; border-top-left-radius:2em; border-bottom-left-radius:2em; }
js代码:
<script type="text/javascript"> // 获取小圆点 var xiaoyuan = document.getElementsByClassName("xiaoyuan"); // 获取装图片的盒子 var imgbox = document.getElementById("imgbox"); // 获取左右箭头 var jiantou = document.getElementsByClassName("jiant"); //小圆点控制图片 xiaoyuan[0].onclick = function () { imgbox.style.left = 0; } xiaoyuan[1].onclick = function () { imgbox.style.left = "-520px"; } xiaoyuan[2].onclick = function () { imgbox.style.left = "-1040px"; } //左箭头控制图片 jiantou[0].onclick = function () { if (imgbox.offsetLeft == 0) { imgbox.style.left = "-1040px"; console.log(imgbox.offsetLeft); } else { imgbox.style.left = imgbox.offsetLeft + 520 + "px"; } } //右箭头控制图片 jiantou[1].onclick = function () { if (imgbox.offsetLeft <= -1040) { console.log(imgbox.offsetLeft); imgbox.style.left = 0; } else { imgbox.style.left = imgbox.offsetLeft - 520 + "px"; } } //定时器控制图片轮播 var fun1 = function () { if (imgbox.offsetLeft <= -1040) { imgbox.style.left = 0; } else { imgbox.style.left = imgbox.offsetLeft - 520 + "px"; } } var t = setInterval(fun1, 2500);//fun1是你的函数 // 鼠标经过停止轮播 imgbox.onmouseover = function () { clearInterval(t) //关闭定时器 } // 鼠标离开开启定时器 imgbox.onmouseout = function () { t=setInterval(fun1,2500)//重新开始定时器 } </script>
版权声明:本文为xiaojuziya原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。