前端JS -定时器 实现图片无缝滚动

时间:2024-10-06 12:53:10
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>无缝滚动</title> <style type="text/css"> body,ul{ margin:0; padding:0; } .list_con{ width:1000px; height:200px; border:1px solid #000; margin:10px auto 0; background-color:#f0f0f0; position:relative; overflow:hidden; } .list_con ul{ list-style:none; width:2000px; height:200px; position:absolute; left:0; top:0; } .list_con li{ width:180px; height:180px; float:left; margin:10px; } .btns_con{ width:1000px; height:30px; margin:50px auto 0; position:relative; } .left,.right{ width:30px; height:30px; background-color:gold; position:absolute; left:-40px; top:124px; font-size:30px; line-height:30px; color:#000; font-family: 'Arial'; text-align:center; cursor:pointer; border-radius:15px; opacity:0.5; } .right{ left:1010px; top:124px; } </style> <script type="text/javascript"> window.onload = function(){ var oLeft = document.getElementById('btn01'); var oRight = document.getElementById('btn02'); var oUl = document.getElementById('list'); var oSlide = document.getElementById('slide'); /* 复制Ul中的li */ oUl.innerHTML = oUl.innerHTML + oUl.innerHTML; var iLeft = 0; var iSpeed = -3; var oTime = setInterval(fnMove,30); function fnMove(){ iLeft += iSpeed; oUl.style.left = iLeft +'px'; if(iLeft <-1000){ iLeft = 0; } if(iLeft > 0){ iLeft = -1000; } } /* 左右两边的滑动按钮设置 */ oLeft.onclick =function(){ iSpeed = -3; } oRight.onclick = function(){ iSpeed = 3; } /* 鼠标悬浮事件 */ oSlide.onmouseover = function(){ clearInterval(oTime); } /* 鼠标离开事件 */ oSlide.onpointerout = function(){ oTime = setInterval(fnMove,30); } } </script> </head> <body> <div class="btns_con"> <div class="left" id="btn01">&lt;</div> <div class="right" id="btn02">&gt;</div> </div> <div class="list_con" id="slide"> <ul id="list"> <li><a href=""><img src="images/" alt="商品图片1"></a></li> <li><a href=""><img src="images/" alt="商品图片2"></a></li> <li><a href=""><img src="images/" alt="商品图片3"></a></li> <li><a href=""><img src="images/" alt="商品图片4"></a></li> <li><a href=""><img src="images/" alt="商品图片5"></a></li> </ul> </div> </body> </html>