简单图片无缝滑动纯JS编写原理

xiaoxiao2021-02-28  31

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en"> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title>Document</title> <style> *{ margin: 0; padding: 0; } .div1{ position: relative;margin:0 auto;overflow: hidden;width:712px; height:108px;background-color: pink; } .move_ul{ list-style: none;position: absolute; } .move_ul li{ float: left;width: 178px;height: 108px; } .l,.le{ margin-right: 100px; } </style> <script> window.onload=function(){ var oDiv=document.getElementsByClassName('div1')[0]; var oUl=document.getElementsByClassName('move_ul')[0]; var aLi=document.getElementsByTagName('li'); var ol=document.getElementsByClassName('l')[0]; var or=document.getElementsByClassName('r')[0]; var le=document.getElementsByClassName('le')[0]; var ri=document.getElementsByClassName('ri')[0]; var timer=null; var speed=2; oUl.innerHTML=oUl.innerHTML+oUl.innerHTML; oUl.style.width=aLi[0].offsetWidth*aLi.length+'px'; function move(){ if(oUl.offsetLeft<-oUl.offsetWidth/2){ oUl.style.left='0'; } if(oUl.offsetLeft>0){ oUl.style.left=-oUl.offsetWidth/2+'px'; } oUl.style.left=oUl.offsetLeft+speed+'px'; } timer=setInterval(move,30); oDiv.onmouseover=function(){ clearInterval(timer); } oDiv.onmouseout=function(){ timer=setInterval(move,30); } ol.onclick=function(){ speed=-2; } or.onclick=function(){ speed=2; } le.onclick=function(){ oUl.style.left=oUl.offsetLeft-aLi[0].offsetWidth+'px'; } ri.onclick=function(){ oUl.style.left=oUl.offsetLeft+aLi[0].offsetWidth+'px'; } } </script> </head> <body> <span class="l">向←滑动</span> <span class="r">向→滑动</span> <br /> <span class="le">左一个</span> <span class="ri">右一个</span> <div class="div1"> <ul class="move_ul"> <li><img src="images/1.jpg" alt="" /></li> <li><img src="images/2.jpg" alt="" /></li> <li><img src="images/3.jpg" alt="" /></li> <li><img src="images/4.jpg" alt="" /></li> </ul> </div> </body> </html>

效果:

 

 

 

 

转载请注明原文地址: https://www.6miu.com/read-2624452.html

最新回复(0)