您现在的位置:首页 >> 前端 >> 内容

轮播封装的初步简单封装代码实现教程

时间:2017/12/20 11:25:26 点击:

  核心提示:html:!DOCTYPE htmlhtml lang=enheadmeta charset=UTF-8titleDocument/titlestyle#banner{width: 500px;ove...

html:

<!DOCTYPE html>  
<html lang="en">  
<head>  
    <meta charset="UTF-8">  
    <title>Document</title>  
    <style>  
        #banner{  
            width: 500px;  
            overflow: hidden;  
        }  
        #imgs{  
            position: relative;  
            width: 3000px;  
        }  
        img{  
            width: 500px;  
        }  
        #ids{  
            position: relative;  
        }  
        .ids_item{  
            width: 10px;  
            height: 10px;  
            border-radius: 50%;  
            border: 4px solid red;  
            float: left;  
            margin-right: 20px;  
            cursor: pointer;  
        }  
    </style>  
</head>  
<body>  
    <p id="banner">  
        <p id="imgs">  
            <img src="img/jj.JPG" alt="">  
            <img src="img/jj1.JPG" alt="">  
            <img src="img/1.png" alt="">  
            <img src="img/2.png" alt="">  
            <img src="img/jj.JPG" alt="">  
        </p>  
        <p id="ids">  
            <p class="ids_item"></p>  
            <p class="ids_item"></p>  
            <p class="ids_item"></p>  
            <p class="ids_item"></p>  
        </ul>  
    </p>  
      
    <script src="js/jquery.min.js"></script>  
    <script src="js/banner.js"></script>  
  
    <script>  
        //图片轮播初步封装  
        //注:需要自己写css样式  
        //第一个参数:id值 注:图片外面的p  
        //第二个参数:id值 注:小圆点  
        //第三个参数:每张图片暂留时间  
        //第四个参数:动画切换所需时间  
        //第五个参数:图片个数(不算最后一张图片,最后一张图片与第一张图片重复)  
        init('imgs','ids',2000,1000,500,4);  
    </script>  
</body>  
</html>  

注:需要引入JQ

banner.js:

var moved=0;  
var WAIT=2000;  
var DURA=1000;  
var $Imgs="";  
var $ids="";  
var imgWidth=500;  
var imgCount=2;  
var timer=null;  
  
function init(id1,id2,wait,dura,wid,count){  
    $Imgs=$('#'+id1);  
    $ids=$('#'+id2);  
    WAIT=wait;  
    DURA=dura;  
    imgWidth=wid;  
    imgCount=count;  
  
    $ids.on("mouseover","p",function(){  
        var $li=$(this);  
        var i=$li.index();  
        moved=i;  
        clearInterval(timer);  
        timer=null;  
        $Imgs.animate({  
                left:-imgWidth*moved  
            },DURA,()=>{}  
        );  
    });  
    $ids.on("mouseout","p",function(){  
        timer=setInterval(move,WAIT);  
    });  
}  
function move(dir=1){  
    moved+=dir;  
    $Imgs.animate({  
        left:-imgWidth*moved  
    },DURA,()=>{  
        if(moved%imgCount==0){  
            moved=0;  
            $Imgs.css("left",0);  
        }  
    })  
}  
var timer=setInterval(move,WAIT);  
  
$("#imgs").hover(  
    ()=>{  
        clearInterval(timer),  
        timer=null;  
    },  
    ()=>{  
        timer=setInterval(move,WAIT);  
    }  
);  
  

作者:网络 来源:spfLinux的博