【原生JS】写最简单的图片轮播

非常简单的一个大图轮播,通过将控制显示位置来进行轮播效果,写来给正在学习的新手朋友们参考交流。

先看效果:(实际效果没有这么快)

 

 

先看布局:

<div id="display">     // 显示容器
<div id="tp" style="left:0px">  // 图片容器一定要加left
<img src="img/lunbo1.png" /> //图片
<img src="img/lunbo2.png" /> //图片
<img src="img/lunbo3.png" /> //图片
</div>
</div>

  

 

布局样式:

<style>
*{margin:0;}
#display{width:1200px; height:500px; margin: 200px auto; overflow: hidden; position: relative;}  //显示区域  宽度和高度为轮播图的宽高
#tp{width:3600px; height:500px; position:absolute;}  //几张图片的长相加的宽  3600像素 高500像素
#tp img{width:1200px; height:500px; float:left;}  // 定义图片大小让图片左浮动
#tp:hover{cursor: pointer;}   //美化鼠标 鼠标秒上去显示手型
</style>

 

  

JS代码:

 

<script language="JavaScript" type="text/javascript">
window.onload = function(){
var tp = document.getElementById('tp');
var timer;                                                            
function lunbo(){                                                 //轮播函数
var leftvalue = parseInt(tp.style.left);                    // 将图片目前样式中的左边像素提取并转为整数
tp.style.left = leftvalue - 1200 + 'px';                    // 使计时器每次操作将图片容器左边减去1200像素
if(leftvalue == -2400){                                        // 判断当前图片左边是否到了最后一张图
tp.style.left = 0 + 'px';                                        //将图片左边重置为0像素,达到无限轮播
}
}
function play(){                                             //启动计时器
timer = setInterval(lunbo,3000);
}
function stop(){                                             //停止计时器
clearInterval(timer);
}
timer = setInterval(lunbo,3000);                    //打开页面后自动启动计时器
box.onmouseover = stop;                              //当鼠标移入显示区域时停止计时器
box.onmouseout = play;                               //当鼠标移出时激活计时器
}

</script>

  


只是做了主体切换代码部分,其于按钮切换等自行通过此思维方法进行添加。

posted @ 2017-03-30 15:38  GruntFish  阅读(533)  评论(0编辑  收藏  举报