>웹 프론트엔드 >JS 튜토리얼 >이미지 캐러셀을 구현하는 js 코드 예제(상세 코드)

이미지 캐러셀을 구현하는 js 코드 예제(상세 코드)

不言
不言원래의
2018-08-09 17:57:156391검색

이 글은 이미지 캐러셀의 js 구현에 대한 코드 예제(상세 코드)를 제공합니다. 필요한 친구들이 참고할 수 있기를 바랍니다.

broadcast.js

var CarouselFigure = new Object();
//轮播图初始化定义函数
CarouselFigure.init = function(tmpobj){
    //定义动画帧数(默认为:30)
    this.frameNum = tmpobj.frameNum !=undefined ?  tmpobj.frameNum : 30;
    //定义一次轮播的时间(默认为:0.2s)
    this.comsumeTime = tmpobj.comsumeTime !=undefined ?  tmpobj.comsumeTime : 200;
    //定义轮播图的宽高(默认宽高为:700px * 250px)
    this.CFWidth = tmpobj.CFWidth !=undefined ?  tmpobj.CFWidth : 700;
    this.CFHeight = tmpobj.CFHeight !=undefined ?  tmpobj.CFHeight : 250;
    //定义轮播的风格
    this.type = tmpobj.type == "small" ? 'small' : 'big';
    //轮播图的按钮大小的宽高
    this.AssowWidth = tmpobj.AssowWidth !=undefined ?  tmpobj.AssowWidth : 76;
    this.AssowHeight = tmpobj.AssowHeight !=undefined ?  tmpobj.AssowHeight : 112;
    //判断用户是否初始化
    this.initFlag = true;
    //是否允许轮播图运行
    this.applicationflag = true;
}
CarouselFigure.start = function(){
/**
    第一部分类容:初始化整个轮播图和其运行数据
*/
(function(){
    //1. 判断用户是否进行初始化
    if(CarouselFigure.initFlag == undefined){
        CarouselFigure.init({});
    }
    
    //2.1 初始化整个轮播图的div的基本大小
    $("#CarouselFigure").width(CarouselFigure.CFWidth).height(CarouselFigure.CFHeight).css("position","relative");
    
    //2.2 最中央的大图实际大小为:
    CarouselFigure.ImgWidth = CarouselFigure.CFWidth * 2/3;
    CarouselFigure.ImgHeight =  CarouselFigure.CFHeight - 6;
    
    //3. 初始化轮播图按钮数据
    CarouselFigure.setAssowdata = {
    prev:{
          top:(CarouselFigure.CFHeight - CarouselFigure.AssowHeight)/2 +"px",
          left:CarouselFigure.CFWidth/6 - CarouselFigure.AssowWidth + 6 + "px",
          originUrl:$("#CarouselFigure > img:eq(0)").attr("src"),
          hoverUrl:$("#CarouselFigure > img:eq(1)").attr("src"),
          },
    next:{
          top:(CarouselFigure.CFHeight - CarouselFigure.AssowHeight)/2 +"px",
          left:CarouselFigure.CFWidth*5/6 + "px",
          originUrl:$("#CarouselFigure > img:eq(2)").attr("src"),
          hoverUrl:$("#CarouselFigure > img:eq(3)").attr("src"),
          }
    };
    
    //4.1 初始化轮播图的url和src信息,存放到一个容器中
    CarouselFigure.imageContains = [];                        
    $("#CarouselFigure ul li img").each(function(){
        var tmpobj = {src:$(this).attr("src"),href:$(this).attr("href")}
        CarouselFigure.imageContains.push(tmpobj);
    });
    //4.2 对轮播图容器数据进行处理,当轮播图的个数3<= x  <= 5 只能使用small风格类型。当轮播图的个数 x < 3 时, 停止运行
    if(CarouselFigure.imageContains.length < 3){
        CarouselFigure.applicationflag = false;
    }else if(CarouselFigure.imageContains.length < 6){
        CarouselFigure.type = &#39;small&#39;;
    }
    //4.3 对轮播容器数据按顺序进行增倍,保证有足够数据进行轮播
    var objstr = JSON.stringify(CarouselFigure.imageContains);
    CarouselFigure.imageContains = CarouselFigure.imageContains.concat(JSON.parse(objstr));
    //5.1 轮播图使用big风格时,页面七张图在静态页面中的属性值
    CarouselFigure.setViewPosData = new Object;
     CarouselFigure.setViewPosData.big = [
        {
            width:CarouselFigure.ImgWidth*3/8,        height:CarouselFigure.ImgHeight*3/8,
            left:0,                                    top:0,
            zIndex:1,            opacity:0.2,        borderSize:0
        },{
            width:CarouselFigure.ImgWidth*3/8,        height:CarouselFigure.ImgHeight*3/8,
            left:0,                                    top:CarouselFigure.CFHeight*5/16,
            zIndex:2,            opacity:0.7,        borderSize:0
        },{
            width:CarouselFigure.ImgWidth*3/4,        height:CarouselFigure.ImgHeight*3/4,
            left:CarouselFigure.CFWidth/18,            top:CarouselFigure.CFHeight/8,
            zIndex:3,            opacity:0.9,        borderSize:0
        },{
            width:CarouselFigure.ImgWidth,            height:CarouselFigure.ImgHeight,
            left:CarouselFigure.CFWidth/6,            top:0,
            zIndex:4,            opacity:1,            borderSize:3
        },{
            width:CarouselFigure.ImgWidth*3/4,        height:CarouselFigure.ImgHeight*3/4,
            left:CarouselFigure.CFWidth * 4/9,        top:CarouselFigure.CFHeight/8,
            zIndex:3,            opacity:0.9,        borderSize:0
        },{
            width:CarouselFigure.ImgWidth*3/8,        height:CarouselFigure.ImgHeight*3/8,
            left:CarouselFigure.CFWidth * 3/4,        top:CarouselFigure.CFHeight*5/16,
            zIndex:2,            opacity:0.7,        borderSize:0
        },{
            width:CarouselFigure.ImgWidth*3/8,        height:CarouselFigure.ImgHeight*3/8,
            left:CarouselFigure.CFWidth * 3/4,        top:0,
            zIndex:1,            opacity:0.2,        borderSize:0
        },];
    //5.2 轮播图使用small风格时,页面5张图在静态页面中的属性值
     CarouselFigure.setViewPosData.small = [
        {
            width:CarouselFigure.ImgWidth*3/8,        height:CarouselFigure.ImgHeight*3/8,
            left:0,                                    top:0,
            zIndex:1,            opacity:0.2,        borderSize:0
        },{
            width:CarouselFigure.ImgWidth*3/4,        height:CarouselFigure.ImgHeight*3/4,
            left:0,                                    top:CarouselFigure.CFHeight/8,
            zIndex:2,            opacity:0.9,        borderSize:0
        },{
            width:CarouselFigure.ImgWidth,            height:CarouselFigure.ImgHeight,
            left:CarouselFigure.CFWidth/6,            top:0,
            zIndex:3,            opacity:1,            borderSize:3
        },{
            width:CarouselFigure.ImgWidth*3/4,        height:CarouselFigure.ImgHeight*3/4,
            left:CarouselFigure.CFWidth * 1/2,        top:CarouselFigure.CFHeight/8,
            zIndex:2,            opacity:0.9,        borderSize:0
        },{
            width:CarouselFigure.ImgWidth*3/8,        height:CarouselFigure.ImgHeight*3/8,
            left:CarouselFigure.CFWidth * 3/4,        top:0,
            zIndex:1,            opacity:0.2,        borderSize:0
        }];
}());
//验证初始化是否成功,否则全部隐藏,结束进程
if(!CarouselFigure.applicationflag){
    $("#CarouselFigure").css("display","none");
    return false;
}
/**
    第二部分:
        对轮播图的箭头进行初始化(包括页面中的静态布局,和点击事件和悬浮事件)
*/
    CarouselFigure.InitAssow = function (Assow,direction){
        //实现轮播图箭头的静态样式、悬浮事件和点击事件
        Assow.css({
            position:"absolute",
            left:this.setAssowdata[direction].left,
            top:this.setAssowdata[direction].top,
            "z-index":4
        })
        .mouseover(function(){            //鼠标悬浮切换图片
            $(this).attr("src",CarouselFigure.setAssowdata[direction].hoverUrl);
        }).mouseout(function(){
            $(this).attr("src",CarouselFigure.setAssowdata[direction].originUrl);
        }).click(function(){
            //记录点击事件的次数
            CarouselFigure.clickArrowfun(direction);    
        });
    }
    //调用初始化轮播图函数--实现左右箭头全部功能
    $("#CarouselFigure > img:odd").css("display","none");
    CarouselFigure.InitAssow($("#CarouselFigure > img:eq(0)"),"prev");
    CarouselFigure.InitAssow($("#CarouselFigure > img:eq(2)"),"next");
/**
    第三部分:
        对所有的轮播图进行页面静态布局
*/
    //初始化某张轮播图的方法
    CarouselFigure.InitImages =    function (i,setViewPosData,imageContains){
        $("#CarouselFigure ul img:eq("+i+")").css({
            position:"absolute",
            width:setViewPosData[i].width + "px",
            height:setViewPosData[i].height + "px",
            top:setViewPosData[i].top + "px",
            left:setViewPosData[i].left + "px",
            display:"block",
            "z-index":setViewPosData[i].zIndex,
            opacity:setViewPosData[i].opacity,    
        }).attr({
            src:imageContains[i].src,
            href:imageContains[i].href
        }).click(function(){
            location.href = $(this).attr("href");    //绑定图片点击跳转事件
        });
        if( (i == 0 || i == 6) && this.type == &#39;big&#39;){        //第1张图片和第7张图片不可见
            $("#CarouselFigure ul img:eq("+i+")").css("display","none");
        }else if(i == 3 && this.type == &#39;big&#39;){                //为正中央图片加边框
            $("#CarouselFigure ul img:eq("+i+")").css("border","3px solid #fff");
        }else if( (i == 0 || i == 4)&&this.type == &#39;small&#39;){//第1张图片和第5张图片不可见
            $("#CarouselFigure ul img:eq("+i+")").css("display","none");
        }else if(i == 2 && this.type == &#39;small&#39;){            //为正中央图片加边框
            $("#CarouselFigure ul img:eq("+i+")").css("border","3px solid #fff");
        }
    }
    /**
        实现七张图片的静态样式:
            清空原有的li标签,然后新建<li><img></li>来存放每张轮播图。
    */
     $("#CarouselFigure ul").empty();
    for(var i = 0; i < CarouselFigure.setViewPosData[CarouselFigure.type].length; i++){
        $("#CarouselFigure ul").append(&#39;<li><img src=""></li>&#39;);
        CarouselFigure.InitImages(i,CarouselFigure.setViewPosData[CarouselFigure.type],CarouselFigure.imageContains);
    } 
/**
    第四部分:
        形成轮播动画效果
*/    
    /*
    设置clickArrow变量:作为动画的标示位,让其进行队列化,必须本次动画完成,才能进行下次动画轮播。
        1. 当为负数时向前轮播,比如:-5向前轮播五次动画;
        2. 当为正数时向后轮播,同理;
        3. 当等于0时,此时没有进行轮播。
    */
    CarouselFigure.clickArrow = 0 ;
    
    // 处理动画队列方法:
    CarouselFigure.clickArrowfun = function (direction){
        if(this.clickArrow == 0){
            this.startAnimation(direction);
        }
        if(direction == "prev"){
            this.clickArrow--;
        }else if(direction == "next"){
            this.clickArrow++;
        }
    }
    /**
        开始一次轮播动画
            其中composerAnimateNum变量为:
                在一次动画中,记录每张轮播图完成的标识符;
                在big风格类型中:当其值为6时说明此次动画全部完成
                在small风格类型中:当其值为4时说明此次动画全部完成
    */ 
    CarouselFigure.startAnimation = function(direction){
        this.completeAnimationNum = 0;
        if(direction == "prev"){        //从最后一张图片到第一张轮播图片,分别向前移动,首先让最后一张图片可视    
            if(this.type == "big"){
                $("#CarouselFigure ul img:eq(6)").css("display","block");
            }else{
                $("#CarouselFigure ul img:eq(4)").css("display","block");
            }
            for(var i = this.setViewPosData[this.type].length - 1 ; i > 0; i --){
                this.startMove(i, this.setViewPosData[this.type][i],this.setViewPosData[this.type][i-1],direction);
            }
        }else if(direction == "next"){//从第一张图片到倒数第二张图片,分别向后移动,首先让第一张轮播图片可视
            $("#CarouselFigure ul img:eq(0)").css("display","block");
            for(var i = 0 ; i < this.setViewPosData[this.type].length - 1; i ++){
                this.startMove(i, this.setViewPosData[this.type][i],this.setViewPosData[this.type][i+1],direction);
            }
        }
    }
    /**
        功能:让一张轮播图从某一个状态变换到另一个状态
            (包括位子、透明度、边框等等属性)
    */
    CarouselFigure.startMove = function (index,startObj,endObj,direction){
        //所有属性的增量
        var increaseLeft = endObj.left - startObj.left;
        var increaseTop  = endObj.top - startObj.top;
        var increaseWidth = endObj.width - startObj.width;
        var increaseHeight = endObj.height - startObj.height;
        var increaseOpacity = endObj.opacity - startObj.opacity;
        var increaseBorderSize = endObj.borderSize - startObj.borderSize;
        var time = this.frameNum;            //共总帧数
        var i = 1;                            //帧数的记步标志索引
        //定义函数:一帧到下一帧的变化过程
        function moveStep(){
            setTimeout(function(){
                var tmpObj = $("#CarouselFigure ul img:eq("+index+")");
                //每一帧时图片的属性改变量
                tmpObj.css({
                    width:startObj.width + (increaseWidth/time) * i + "px",
                    height:startObj.height + (increaseHeight/time) * i + "px",
                    top:startObj.top + (increaseTop/time) * i + "px",
                    left:startObj.left + (increaseLeft/time) * i + "px",
                    border:startObj.borderSize + (increaseBorderSize/time) * i + "px solid #fff",
                    opacity:startObj.opacity + (increaseOpacity/time) * i,
                });
                //当小于30帧时,继续递归,直至调用30次完成动画效果
                if( i++ <time){
                    if(i == 15){//轮播图每张图片的层级关系处理方式
                        var zIndex = new Object;
                        zIndex.big = {prev:[null,1,2,3,4,3,2],next:[2,3,4,3,2,1]};
                        zIndex.small = {prev:[null,1,2,3,2,1],next:[2,3,2,1]}
                        tmpObj.css("z-index",zIndex[CarouselFigure.type][direction][index]);
                    }
                    moveStep();                        //递归
                }else{
                    CarouselFigure.completeAnimation(direction);    //完成一张图片的动画
                }
            },CarouselFigure.comsumeTime/time);
        }
        moveStep();                                    //开始动画
    }
/**
    第五部分:
        当每次轮播动画结束后的处理函数
        1. 首先,判断一次轮播动画是否结束;
        2. 对容器数据(imageContains)进行调整,形成队列
        3. 重新渲染整个轮播图的静态页面
        4. 通过clickArrow,处理动画队列
*/    
    CarouselFigure.completeAnimation = function(direction){
        this.completeAnimationNum++;
        //表示完成一次动画
        if(this.completeAnimationNum == (this.setViewPosData[this.type].length -1)){
            //重构用户自定义数据的顺序;
            if(direction == "prev"){
                var tmp = this.imageContains.shift();
                this.imageContains.push(tmp);
            }else if(direction == "next"){
                var tmp = this.imageContains.pop();
                this.imageContains.unshift(tmp);
            }
            //重新渲染轮播图七张图片的静态样式
            for(var i = 0; i < this.setViewPosData[this.type].length; i++){
                this.InitImages(i,this.setViewPosData[this.type],this.imageContains);
            } 
            //解决边框的bug的问题
            if(this.type == &#39;big&#39;){
                $("#CarouselFigure ul li img:even").css("border","0px");
            }else{
                $("#CarouselFigure ul li img:odd").css("border","0px");
            }
            //处理动画队列
            if(direction == "prev"){
                this.clickArrow++;
            }else if(direction == "next"){
                this.clickArrow--;
            }
            if(this.clickArrow > 0){
                this.startAnimation(direction);
            }else if(this.clickArrow < 0){
                this.startAnimation(direction);
            }
        }
    }
};

broadcast.html

<!DOCTYPE html>
<html>
    <head>
        <meta charset="UTF-8">
        <title>轮播图实例</title>
    <script src="js/jquery-3.3.1.min.js"></script>
    </head>
    <style>
    *{
        padding:0px;
        margin:0px;
    }
    ul{
        list-style:none;
    }
    body{
        background:#eee;
        padding:10px;
    }
    #CarouselFigure{
        
    }
    </style>
    <body>
        <div id="CarouselFigure">
            <img src="img/prev.png" width="76" height="112" />
            <img src="img/prev.png" />
            <img src="img/next.png" width="76" height="112" />
            <img src="img/next.png" />            
            <ul>
                <li><img src="img/1.jpg" width="500" height="250"></li>
                <li><img src="img/2.jpg"></li>
                <li><img src="img/3.jpg"></li>
                <li><img src="img/4.jpg"></li>
                <li><img src="img/5.jpg"></li>
                <li><img src="img/6.jpg"></li>
                <li><img src="img/7.jpg"></li>
                <li><img src="img/8.jpg"></li>
            </ul>
        </div>
    </body>
</html>
<script src="js/broadcast.js"></script>
<script>
    $(function(){
        //对轮播图进行初始化
        CarouselFigure.init({type:&#39;small&#39;,comsumeTime:1000});
        CarouselFigure.start();
    })
</script>

성취 효과

관련 권장 사항:

간단한 js 코드를 사용하여 회전식 스크롤 효과를 얻는 방법은 무엇인가요?

koa-router란 무엇인가요? koa-router의 일반적인 구조와 동작과정에 대한 자세한 설명

위 내용은 이미지 캐러셀을 구현하는 js 코드 예제(상세 코드)의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.