左右水平轮播,渐变轮播

左右水平轮播

CSS部分

先写出html结构,原则上是尽量少的标签就能达到功能

    <div class="carousel">
        <ul class="img-ct">
            <li data-id="0"><a href="#">![](http://upload-images.jianshu.io/upload_images/7113407-2822b6ff0ee054f9.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li data-id="1"><a href="#">![](http://upload-images.jianshu.io/upload_images/7113407-0ea8f1080ca906ff.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li data-id="2"><a href="#">![](http://upload-images.jianshu.io/upload_images/7113407-f10834a83445c57c.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
            <li data-id="3"><a href="#">![](http://upload-images.jianshu.io/upload_images/7113407-41418e1d0026658d.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
        </ul>
        <a href="#" class="pre arrow"><</a>
        <a href="#" class="next arrow"></a>
        <ul class="bullet">
            <li class="active"></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
    </div>

设定CSS样式。想要水平轮播,那么几个li必须是水平布局,可以使用float来进行布局。
使元素进行位移一般有margin,relative以及绝对定位几种方式,要轮播显然使用绝对定位

    * {
        margin: 0;
        padding: 0;
        list-style-type: none;
        box-sizing: border-box;
    }
    a {
        text-decoration: none;
    }
    .clearfix:after {
        content: '';
        display: block;
        clear: both;
    }
    /*使元素进行位移一般有margin,relative以及绝对定位几种方式,要轮播显然使用绝对定位*/
    .carousel {
        position: relative;
        width: 400px;
        height: 250px;
        overflow: hidden;

        top: 50px;
        /*设置carousel显露出来的部分水平居中*/
        left: 50%;
        transform: translate(-50%);
    }
    .carousel .img-ct {
        width: 1600px;
        position: absolute;
    }
    .carousel .img-ct img {
        width: 400px;
        height: 250px;
    }
    .carousel .img-ct>li {
        float: left;
    }

    .carousel .arrow {
        position: absolute;
        width: 50px;
        height: 50px;
        border: 1px solid #fff;
        border-radius: 50%;
        top: 50%;
        margin-top: -25px;
        color: #fff;
        line-height: 50px;
        text-align: center;
        font-size: 22px;
    }
    .carousel .arrow:hover {
        background: rgba(0,0,0,0.1);
    }
    .carousel .pre{
        left: 10px;
    }
    .carousel .next {
        right: 10px;
    }

    .carousel .bullet {
        position: absolute;
        width: 100%;
        top: 87%;
        text-align: center;
    }
    .carousel .bullet>li {
        display: inline-block;
        width: 25px;
        height: 5px;
        border: 1px solid #ccc;
        border-radius: 5px;
        cursor: pointer;
    }
    .carousel .bullet>li.active {
        background: #ccc;
    }

JS部分

轮播的思路大概是:比如说只有3张图片1,2,3那么在1到2到3的过程中,只需要设置上述例子的.img-ct的left属性,使其左右平移,就能达到水平切换的效果。但是在切换到底,即3又要轮播回1的时候,一般来说我们不进行DOM顺序的切换。而是在页面一开始初始化时,就创建头和尾两个元素的备份,头元素进行克隆,然后放到最尾部,尾元素克隆之后放到最前面。即创建头尾备份,头备份放到尾部,尾备份放到头部。这样在切换的时候,尾部要轮播到头部的话,其实是轮播到了头部的备份,这个备份是在最尾部即尾元素的下一个的,所以就不需要转换DOM顺序。然后我们在整体移到真正的元素上。
另外我们还需要知道轮播的元素的个数以及每个元素的宽度(水平轮播)
总计一下:

  • 创建头尾元素的备份,头备份放到最后面,尾备份放到最前面。
  • 得到轮播元素的个数和宽度

另外关于jquery的一个特点,jq选择匹配元素只会选择当时定义的元素,如果选择元素在之后的操作中发生变化,当时已经定义的jq元素并不会随着进行动态变化。例如下面的例子使用jq获得了$imgs,然后这个$imgs就一直都是4个元素,就是当时的那4个轮播元素,后面的$('.carousel .img-ct>li')发生了变化,长度增加了,但是当时定义的$imgs不会变化。但是此时再去使用$('.carousel .img-ct>li')就会得到当前的jq对象。

轮播的js代码:

<script src="../jquery-3.2.1.min.js"></script>
    <script>
        var $imgct = $('.img-ct')
        var $imgs = $('.carousel .img-ct>li');
        var imgCount = $imgs.length;  //得得到轮播元素的个数
        var imgWidth = $imgs.width(); //得到轮播元素的宽度
        var $preBtn = $('.pre');
        var $nextBtn = $('.next');
        var $bullets = $('.bullet>li');

        var pageIndex = 0; // 记录轮播的状态,表示在第几页了   当前是第0页
        var animating = false; //用来判断是否还在动画中,来屏蔽多次连续点击

        $imgct.append($imgs.eq(0).clone()); //克隆头元素放到最后面
        //在这里有一个问题,上面使用jq获得了$imgs,现在的$imgs还是4个元素,就是当时的那4个轮播元素,但是此时的$('.carousel .img-ct>li')已经是5个元素了
        $imgct.prepend($imgs.last().clone()); //克隆尾元素放到最前面
        //此时css中,原先是4个li并排的,现在又多了2个头尾备份,因为我们写死了img-ct的宽度,所以剩下2个li挤到了第二排,所以不应该在css中写死宽度。
        $imgct.width((imgCount+2) * imgWidth); //js中设置img-ct的宽度
        //此时展示的是备份的尾元素,我们想让用户看到第一张,那就让img-ct向左移动一个li元素的宽度
        $imgct.css({
            left: -imgWidth
        });
        //然后进行事件的绑定
        $preBtn.on('click',function () {
            playPre(1);
        })
        $nextBtn.on('click',function () {
            playNext(1);
        })
        //设置bullets的跳转
        $bullets.on('click',function () {
            var index = $(this).index(); //拿到当前点击的那个bullet是第几个
            if (index > pageIndex) {
                playNext(index - pageIndex);
            }
            else if (index < pageIndex){
                playPre(pageIndex - index);
            }
        })
        function playNext (num) {
            if (animating) {
                return; // 如果还在动画中直接return掉
            }
            animating = true; //设置为动画中
            $imgct.animate({
//                left: -imgWidth, // 这时候不能写成这样,因为初始时候的left就是负的imgWidth,而且这么写图片是不会动。应该是写成left: -= imgWidth的形式
                left: '-='+ num * imgWidth, // 因为jq没有left: -=imgWidth这样的写法,所以写成这样
            },function () {
                pageIndex += num; // 在animate的完成函数里进行pageIndex的增加和减小
                if (pageIndex === imgCount) { //如果当前页码到了最后面,即头备份时,立即让pageIndex为0,然后页面回到一开始的位置
                    pageIndex = 0;
                    $imgct.css({
                        left: -imgWidth,
                    })
                }
                setBullet();
                animating = false;
            })

        }
        //同理playPre写为
        function playPre (num) {
            if (animating) {
                return;
            }
            animating = true;
            $imgct.animate({
                left: '+='+ num * imgWidth, // 因为jq没有left: +=imgWidth这样的写法,所以写成这样
            },function () {
                pageIndex -= num;
                if (pageIndex === -1) {
                    pageIndex = 3;
                    $imgct.css({
                        left: -4*imgWidth,
                    })
                }
                setBullet();
                animating = false;
            })

        }
    //设置下面的bullet跳转
        function setBullet () {
            $bullets.removeClass('active')
                    .eq(pageIndex).addClass('active');
        }


    </script>

渐变轮播

渐变轮播相对较简单,核心思想是让4个li重叠在一起,可以通过设置position:absolute;达到。然后通过变量监控当前元素的次序,通过fadeIn()和fadeOut()实现效果。

css部分只有.img-ct>li设为position:absolute;改变。

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>渐变轮播</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
        list-style-type: none;
        box-sizing: border-box;
    }
    a {
        text-decoration: none;
    }
    .clearfix:after {
        content: '';
        display: block;
        clear: both;
    }
    /*使元素进行位移一般有margin,relative以及绝对定位几种方式,要轮播显然使用绝对定位*/
    .carousel {
        position: relative;
        width: 400px;
        height: 250px;
        overflow: hidden;

        top: 50px;
        /*设置carousel显露出来的部分水平居中*/
        left: 50%;
        transform: translate(-50%);
    }
    .carousel .img-ct {
        /*width: 1600px;*/
        position: absolute;
    }
    .carousel .img-ct img {
        width: 400px;
        height: 250px;
    }
    .carousel .img-ct>li {
        /*通过设置绝对定位,使得所有的li都脱离文档里重合在一起*/
        position: absolute;
        display: none;
    }

    .carousel .arrow {
        position: absolute;
        width: 50px;
        height: 50px;
        border: 1px solid #fff;
        border-radius: 50%;
        top: 50%;
        margin-top: -25px;
        color: #fff;
        line-height: 50px;
        text-align: center;
        font-size: 22px;
    }
    .carousel .arrow:hover {
        background: rgba(0,0,0,0.1);
    }
    .carousel .pre{
        left: 10px;
    }
    .carousel .next {
        right: 10px;
    }

    .carousel .bullet {
        position: absolute;
        width: 100%;
        top: 87%;
        text-align: center;
    }
    .carousel .bullet>li {
        display: inline-block;
        width: 25px;
        height: 5px;
        border: 1px solid #ccc;
        border-radius: 5px;
        cursor: pointer;
    }
    .carousel .bullet>li.active {
        background: #ccc;
    }
</style>
<body>

<div class="carousel">
    <ul class="img-ct clearfix">
        <li data-id="0"><a href="#">![](http://upload-images.jianshu.io/upload_images/7113407-8fb0bf6748ea96ce.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
        <li data-id="1"><a href="#">![](http://upload-images.jianshu.io/upload_images/7113407-c14f4c5e00f198d1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
        <li data-id="2"><a href="#">![](http://upload-images.jianshu.io/upload_images/7113407-6eaedb71aecbdeb1.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
        <li data-id="3"><a href="#">![](http://upload-images.jianshu.io/upload_images/7113407-799af87ca1adff72.jpg?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)</a></li>
    </ul>
    <a href="#" class="pre arrow"><</a>
    <a href="#" class="next arrow">></a>
    <ul class="bullet">
        <li class="active"></li>
        <li></li>
        <li></li>
        <li></li>
    </ul>
</div>

<script src="../jquery-3.2.1.min.js"></script>
<script>
    var $imgct = $('.img-ct');
    var $imgs = $('.carousel .img-ct>li');
    var imgWidth = $imgs.width();
    var imgCount = $imgs.length;
    var $pre = $('.pre');
    var $next = $('.next');
    var $bullets = $('.bullet>li');
    var currentIndex = 0;  //记录当前页码
    var animating = false; //针对连续重复点击,设置变量来监听是否处于动画过程中


    play();
    $pre.on('click',function () {
        playPre();
    })
    $next.on('click',function () {
        playNext();
    })
    $bullets.on('click',function () {
        var index = $(this).index();
        console.log('index为',index)
        currentIndex = index;
        console.log('pageIndex为',currentIndex)
        setBullets();
        $imgs.fadeOut();
        $imgs.eq(index).fadeIn();
    })
    function playPre () {
        $imgs.eq(currentIndex).fadeOut();
        console.log('进入时的index',currentIndex);
        if (currentIndex === 0) {
            currentIndex = imgCount;
            console.log('if时的index',currentIndex);
        }
        $imgs.eq(currentIndex-1).fadeIn();
        currentIndex--;
        setBullets();
        console.log('退出时的index',currentIndex);
    }
    function playNext () {
        $imgs.eq(currentIndex).fadeOut();
        console.log('进入时的index',currentIndex);
        if (currentIndex === imgCount-1) {
            currentIndex = -1;
            console.log('if时的index',currentIndex);
        }
        $imgs.eq(currentIndex+1).fadeIn();

        currentIndex++;
        setBullets();
        console.log('退出时的index',currentIndex);
    }
    function setBullets () {
        $bullets.removeClass('active')
                .eq(currentIndex).addClass('active');
    }
    function play() {
        $imgs.eq(currentIndex).fadeIn(); //页面一加载时,先让第一个元素显露出来
        setInterval(function () {
            playNext();
        },1000)
    }
</script>
</body>
</html>

JS部分先不考虑自动轮播,先进行事件绑定,然后想着先把playPre()和playNext()以及setBullets ()实现,然后设置一个setInterval即可。需要注意的是页面初始化的时候是空白的。写一句$imgs.eq(currentIndex).fadeIn(); 让第一个元素显现出来。优化的时候统一加到play()中即可。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,716评论 4 364
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,558评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,431评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,127评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,511评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,692评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,915评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,664评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,412评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,616评论 2 245
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,105评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,424评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,098评论 3 238
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,096评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,869评论 0 197
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,748评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,641评论 2 271

推荐阅读更多精彩内容