原生js做轮播
HTML代码:
<div id="scroll" class="scroll"> <div id="box" class="box"> <ul id="ul"> <li><img src="image/1.png" width="500" height="200"></li> <li><img src="image/2.png" width="500" height="200"></li> <li><img src="image/3.png" width="500" height="200"></li> <li><img src="image/4.png" width="500" height="200"></li> <li><img src="image/5.png" width="500" height="200"></li> </ul> <!--<ol id="ol"> <li class="current">1</li> <li>2</li> <li>3</li> <li>4</li> <li>5</li> </ol>--> </div> </div>
css代码:
<style type="text/css"> *{ margin: 0px; padding: 0px; } ul,ol{ list-style: none; } img{ vertical-align: top; } .scroll{ width: 500px; height: 200px; margin: 100px auto; border: 1px solid #ccc; padding: 7px; overflow: hidden; position: relative; } .box{ width: 500px; height: 200px; position: relative; overflow: hidden; } .box ul{ width: 600%; position: absolute; left: 0px; top: 0px; } .box ul li{ float: left; } .scroll ol{ position: absolute; bottom: 10px; right: 10px; } .scroll ol li{ float: left; width: 20px; height: 20px; background: pink; border-radius: 50%; text-align: center; margin-left: 10px; cursor: pointer; } .scroll ol li.current{ background: purple; } </style>
js代码:
<script type="text/javascript"> //数字下标并非写死,是根据图片张数自动生成 var scroll = document.getElementById('scroll');//获得大盒子 var ul = document.getElementById('ul');//获得ul var ulList = ul.children;//获得ul下的li var listWidth = ul.children[0].offsetWidth; //克隆一张图片并放在最后一张 ul.appendChild(ul.children[0].cloneNode(true)); //生成ol小圆点 var ol = document.createElement('ol'); //追加到scroll 里面 scroll.appendChild(ol); for(var i = 0;i<ulList.length-1;i++){ var li = document.createElement('li'); li.innerHTML = i+1; //把li追加到ol里面 ol.appendChild(li); } var olList = ol.children; //当前颜色加一个类名 ol.children[0].className = "current"; //动画函数 function animate(obj,target){ //清除定时器 clearInterval(obj.timer); var speed = obj.offsetLeft<target ? 15: -15; obj.timer = setInterval(function(){ var result = target - obj.offsetLeft;//差值不会超过speed obj.style.left = obj.offsetLeft + speed +"px"; //有可能会出现小数点,这里要做判断 if(Math.abs(result) <= Math.abs(speed)){ clearInterval(obj.timer); obj.style.left = target +"px"; } },10); } //开始写轮播逻辑 var timer = null;// 轮播图的定时器 var key = 0;//控制播放的张数 var circle = 0;//控制小圆点 //轮播函数 timer = setInterval(autoplay,2000); function autoplay(){ key++; if(key > ulList.length - 1){ ul.style.left = 0; key = 1; } animate(ul,-key*listWidth); circle++; if(circle > olList.length - 1){ circle = 0; } for(var i = 0;i<olList.length;i++){ olList[i].className = ""; } olList[circle].className = "current"; } </script>
根据这些代码运行出来的效果是这样的:
无才难做千里马,有志可吞九霄云!