2018.07.30js实现轮播图
javascript实现轮播图
一、html代码
<body>
<center>
<button onClick="pgup()">上一页</button>
<img src="../20180728/2.png" alt="" width="450" height="350">
<button onClick="pgdn()">下一页</button><br>
<img src="../20180728/3.png" alt="" width="50" height="50">
<img src="../20180728/4.png" alt="" width="50" height="50">
<img src="../20180728/5.png" alt="" width="50" height="50" xb="3" onClick="showme(this)">
</center>
</body>
二、javascript代码
<script>
//轮播图
var img=null;//定义图片
var k=0;//定义下标
var dsq=null;//定义定时器
var imgs=['../20180728/2.png','../20180728/3.png','../20180728/4.png','../20180728/5.png'];
window.onunload=function(){
}
//获取图片
img=document.getElementsByTagName('img')[0];
//定义鼠标移入和鼠标移出事件
img.onmouseover=stop;
img.onmouseout=start;
//上一页
function pgup(){
k++;
if(k>=imgs.length){
k=0;
}img.setAttribute("src",imgs[k]);
}
//下一页
function pgdn(){
k--;
if(k<=0){
k=imgs.length-1;
}img.setAttribute("src",imgs[k]);
}
//定时器(连环炸弹)
dsq=setInterval(function(){
pgdn();
},5000);
//鼠标移出时图片开始轮播
function start(){
dsq=setInterval(function(){
pgdn();
},5000);
}
//鼠标移入时图片停止播放
function stop(){
clearInterval(dsq);
}
//点击小图时切换图片
function showme(obj){
k=+obj.getAttribute('xb');
img.setAttribute("src",imgs[k]);
}
</script>