学习前端也有一小段时间了,当初在学习javascript的时候,练手的一个轮播图实例,轮播图也是挺常见的了。
着是通过获取图片偏移量实现的。也实现了无缝切换。还有一点问题就是没有加上图片切换的时候的延迟了,哈哈
html:
- 1 <div id="container">
- 2 <div id="list" style="left: -600px;">
- 3 <img src="../image/1.jpg" alt="5">
- 4 <img src="../image/1.jpg" alt="1">
- 5 <img src="../image/2.jpg" alt="2">
- 6 <img src="../image/3.jpg" alt="3">
- 7 <img src="../image/4.jpg" alt="4">
- 8 <img src="../image/5.jpg" alt="5">
- 9 <img src="../image/1.jpg" alt="1">
- 10 </div>
- 11 <div id="buttons">
- 12 <span class="on"></span>
- 13 <span></span>
- 14 <span></span>
- 15 <span></span>
- 16 <span></span>
- 17 </div>
- 18 <a href="javascript:;" id="prev" class="arrow"><</a>
- 19 <a href="javascript:;" id="next" class="arrow">></a>
- 20 </div>
js:
- 1 window.onload = function(){
- 2 //获取元素
- 3 var container = document.getElementById('container');
- 4 var list = this.document.getElementById('list');
- 5 var buttons = document.getElementById('buttons').getElementsByTagName('span');
- 6 var prev = document.getElementById('prev');
- 7 var next = document.getElementById('next');
- 8 var index = 1;//默认第一个小圆点亮
- 9
- 10 //小圆点的点亮
- 11 function showButton() {
- 12 //遍历小圆点的个数,当触发onclick事件后,className为‘on’的变为‘’。
- 13 for(var i = 0;i < buttons.length; i++){
- 14 if(buttons[i].className == 'on'){
- 15 buttons[i].className = '';
- 16 break;
- 17 }
- 18 }
- 19 buttons[index - 1].className = 'on'; //原始第一个小圆点点亮,onclick事件触发后,index+1
- 20 }
- 21
- 22 function animate (offset) {
- 23 //获取从第一张图片开始发生的偏移量
- 24 var newLift = parseInt(list.style.left) + offset;
- 25 list.style.left = newLift + 'px';
- 26 if(newLift > -600){
- 27 //如果偏移量的位置大于-600的时候,图片跳转到第五张图片
- 28 list.style.left = -3000 + 'px';
- 29 }
- 30 if(newLift < -3000){
- 31 //如果偏移量的位置大于-3000的时候,图片跳转到第一张图片
- 32 list.style.left = -600 + 'px';
- 33 }
- 34 }
- 35 next.onclick = function () {
- 36 //如果button的index为5的时候,再点击next按钮会返回 1;
- 37 if(index == 5){
- 38 index = 1;
- 39 }else{
- 40 index += 1;
- 41 }
- 42 showButton();
- 43 animate(-600);
- 44 }
- 45 prev.onclick = function () {
- 46 if(index == 1){
- 47 index = 5;
- 48 }else{
- 49 index -= 1;
- 50 }
- 51 showButton();
- 52 animate(600);
- 53 }
- 54 }