简单的js轮播图代码

2017-05-24  本文已影响0人  忧兰成伤

···
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<style>
ul{
list-style: none;
padding: 0;
margin: 0;
}
#play_box{
position: relative;
width: 670px;
height: 240px;
border: 1px solid #ccc;
}
#play_box img{
display: none;
}
#play_box img.current{
display: block;
}
#iconlist{
position: absolute;
bottom: 10px;
right: 20px;
}
#iconlist li{
float: left;
margin-left: 5px;
width: 26px;
height: 26px;
color: #fff;
text-align: center;
line-height: 26px;
background: #999;
border-radius: 13px;
cursor: pointer;

    }

    #iconlist li.current{
        background: red;
    }
</style>

</head>
<body>
<h1>轮播图</h1>



<div id="play_box">
<div class="imagelist">





</div>
<div id="iconlist">
<ul>
<li class="current">1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
</ul>
</div>
</div>
<script>
//获取所以图片的一个集合
var play_box=document.getElementById('play_box');
var images = play_box.getElementsByTagName('img');
var iconlist = play_box.getElementsByTagName('li');
    var timer = setInterval(run,1000);
    
    var m = 1; //定义循环变量
    //循环函数
    function run(){
        
        if(m > 4){
           m = 0;
        }
        
         //控制图片的变换
        controImage(m); 
        //控制按钮变换
        controIcon(m);
        m++;
    }

    //定义函数 控制图片变化
    function controImage(n){
        //所有的图片隐藏
        //第n个图片显示
        for(var i = 0;i<images.length; i++){
            images[i].className = '';
            
        }
    
        images[n].className = 'current';
        
    }

    //定义函数 控制按钮变换
    function controIcon(n){
        //所以按钮变灰
        //第n个按钮变红
        for(var i = 0 ;i <iconlist.length;i++){
            iconlist[i].className = '';
        }
        iconlist[n].className ='current';
    }
    //鼠标滑过 定时停止
    play_box.onmouseover = function(){
        clearInterval(timer);
    }
    //鼠标移走 继续定时
    play_box.onmouseout = function (){
        timer = setInterval(run,1000);
    }

    //给按钮绑定  鼠标滑过事件 
    for(var i = 0;i <iconlist.length; i++){
        (function(i){
            iconlist[i].onmouseover = function(){
                controIcon(i);
                controImage(i);
                m = i +1;
            }
        })(i)
    }
</script>

</body>
</html>
···

上一篇下一篇

猜你喜欢

热点阅读