资讯专栏INFORMATION COLUMN

小白成长日记:一步一步写个轮播图插件

notebin / 390人阅读

摘要:并不是所有人写的代码或者插件都适合小白使用,比如这是一个的滚动插件,大多数人使用了之后发现滚动不了,去作者提,其实是他们并不懂滚动的原理。

最近在这里看了一篇关于面试的文章《回顾自己三次失败的面试经历》,作者三次倒在了轮播图上。囧,所以我也写个轮播图看看。
这次是用jQuery写的,因为最近一直在研究jQuery插件的写法,所以用jQuery写的,而且我发现,我vue用太多,完全不熟悉dom操作,以后还是要多多用用jQuery和原生js

献给小白们:jQuery插件开发精品教程,让你的jQuery提升一个台阶

html



    
    slide
    
    
    


    

首先的插件的大体结构如下

;(function($, window, document, undefined) {
    var pluginName = "Slide",
    defaults = {
        
    };
    function Slide(element, options) {
        this.element = element;
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.version = "v1.0.0";
        this.init();
    }
    Slide.prototype = {
        init: function() {
            
        }       
    };
    $.fn[pluginName] = function(options) {
        this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Slide(this, options));
            }
        });
        return this;
    };
})(jQuery, window, document);

接下来就是轮播图的大致逻辑了。

主体 初始化,动起来

由简入繁的写,第一步是考虑怎么让轮播图动起来

轮播图在网页上大致是这个样子的,只有一张暴露在视野内,其他的在视野外,用overflow:hidden隐藏就行。
那动起来就非常简单

$(element).animate({right:index*this.width+"px"}, 1000)//jQuery中animate方法

初始化的话,我们需要计算整个ul的长度,获取单个li的长度。

丐中丐版轮播图
;(function($, window, document, undefined) {
    var pluginName = "Slide",
    defaults = {
        
    };
    function Slide(element, options) {
        this.element = element;
        this.width = $(this.element).find("ul li img")[0].width;//图片宽度
        this.length = $(this.element).find("ul li").length//轮播数量
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.version = "v1.0.0";
        this.init();
    }
    Slide.prototype = {
        init: function() {
            let index=1//索引
            const content = $(this.element).find("ul");//获取ul
            content.css("width",this.width*this.length);//计算长度
            this.autoplay(content,index)
        },
        autoplay: function(content,index) {
            const _this=this;
            timer=setInterval(function(){
                $(content).animate({right:index*this.width+"px"}, 1000)
                index++
            },2000)
        }       
    };
    $.fn[pluginName] = function(options) {
        this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Slide(this, options));
            }
        });
        return this;
    };
})(jQuery, window, document);

到这里,轮播图已经在一张图一张图的往右跑了,轮播图的逻辑就这么多。但是别人的轮播图都会回头啊,这个轮播图跑着跑着白屏了。接下来就让他回头,利用声明的index实现。

乞丐版轮播图
;(function($, window, document, undefined) {
    var pluginName = "Slide",
    defaults = {
        
    };
    function Slide(element, options) {
        this.element = element;
        this.width = $(this.element).find("ul li img")[0].width;//图片宽度
        this.length = $(this.element).find("ul li").length//轮播数量
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.version = "v1.0.0";
        this.init();
    }
    Slide.prototype = {
        init: function() {
            let index=1//索引
            const content = $(this.element).find("ul");//获取ul
            content.css("width",this.width*this.length);//计算长度
            this.autoplay(content,index)
        },
        autoplay: function(content,index) {
            const _this=this;
            timer=setInterval(function(){
                $(content).animate({right:index*this.width+"px"}, 1000)
                index===this.length-1?index=0:index++//如果索引到了this.length-1,说明到了最后一张图片,我们将index调为0,下一次运行时,ul的样式就会归位,这样就成功回头
            },2000)
        }       
    };
    $.fn[pluginName] = function(options) {
        this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Slide(this, options));
            }
        });
        return this;
    };
})(jQuery, window, document);

这边已经实现了一个像模像样的轮播图了,但在尾->首切换的时候违和感太严重了,我们需要的是平滑过渡,曾经我绞尽脑汁想不出办法,然后花了半分钟上网搜索到了答案,下次再也不瞎想了。

如上图,在轮播图最后复制一个轮播图第一张,当划到最后一个slide1时,再立即将ul位置复原,切换到第一个slide1,我们以为划到了第一个slide1,这样就能实现平滑的过渡。

无产阶级轮播图
;(function($, window, document, undefined) {
    var pluginName = "Slide",
    defaults = {
        
    };
    function Slide(element, options) {
        this.element = element;
        this.width = $(this.element).find("ul li img")[0].width;//图片宽度
        this.length = $(this.element).find("ul li").length//轮播数量
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.version = "v1.0.0";
        this.init();
    }
    Slide.prototype = {
        init: function() {
            let index=1//索引
            const content = $(this.element).find("ul");//获取ul
            content.css("width",this.width*this.length);//计算长度
            this.autoplay(content,index)
        },
        autoplay: function(content,index) {
            const _this=this;
            timer=setInterval(function(){
                $(content).animate({right:index*_this.width+"px"}, 1000)
                if(index===_this.length){
                    $(content).animate({right:0+"px"}, 0)//将ul回复到原位
                    index=1//index重置为1(这里是1,恢复到函数刚开始的索引)
                }else{
                    index++
                }
            },2000)
        },
        creat: function(){
            $($(this.element).find("ul li")[0]).clone().appendTo($(this.element).find("ul"))
        },//克隆第一个li再添加到ul       
    };
    $.fn[pluginName] = function(options) {
        this.each(function() {
            if (!$.data(this, "plugin_" + pluginName)) {
                $.data(this, "plugin_" + pluginName, new Slide(this, options));
            }
        });
        return this;
    };
})(jQuery, window, document);

好的,完整版的轮播图就完成了,如果对轮播图没有任何需要,大致就是这样了。但我们网站中的轮播图多种多样,用过插件的小伙伴也知道,很多轮播图能自定义参数来开启不同的功能,例如强大的swiper插件。接下来我们就来实现一些自定义的功能。

贫农版轮播图

自定义参数:轮播间隔时间,轮播分页小点

;(function($, window, document, undefined) {
    var pluginName = "Slide",
    defaults = {//默认参数
        pagination:true,//默认开启轮播分页小点
        interval:2000//默认间隔时间2s
    };//这里不明白的小白朋友们麻烦去通读上面推荐的jquery插件的写法,就会明白
    function Slide(element, options) {
        this.element = element;
        this.width = $(this.element).find("ul li img")[0].width;//图片宽度
        this.length = $(this.element).find("ul li").length//轮播数量
        this.settings = $.extend({}, defaults, options);
        this._defaults = defaults;
        this._name = pluginName;
        this.version = "v1.0.0";
        this.init();
    }
    Slide.prototype = {
        init: function() {
            let index=1;
            this.creat();
            this.settings.pagination?this.pagination():""//如果设置了pagination:true,创建小点
            this.addStyle(0)//给第一个小点添加样式
            const content = $(this.element).find("ul");//获取ul
            content.css("width",this.width*this.length);//计算长度
            this.autoplay(content,index)
        },
        autoplay: function(content,index) {
            const _this=this
            timer=setInterval(function(){
                console.log(index*this.width)
                $(content).animate({right:index*_this.width+"px"}, 1000)
                if(index===_this.length){
                    $(content).animate({right:0+"px"}, 0)
                    index=1
                }else{
                    index++
                }
                _this.addStyle(index-1)//index变化,导致小点样式变化
            },this.settings.ininterval)//将自定义时间传入
        },
        creat: function(){
            $($(this.element).find("ul li")[0]).clone().appendTo($(this.element).find("ul"))
        },
        pagination: function(index){
            let ol="
    " $(this.element).append(ol) let li="
  1. " for(i=1;i

    接下来就是改变下调用

    $(function() {
        $(".contain").Slide({
                pagination:false,
                interval:5000
            })
        })

    这里就起作用了。
    如果再有其他的功能,只需要往里面一步一步添加函数就可以了,比如前进后退按钮,比如一次滚动多张图片。

    小结

    之所以要自己写一写这些小demo,是为了有助于我们更好的使用别人的代码。并不是所有人写的代码或者插件都适合小白使用,比如better-scroll,这是一个vue的滚动插件,大多数人使用了之后发现滚动不了,去作者github提issue,其实是他们并不懂滚动的原理。我之前也是摸索了作者的实例才成功使用的,但这个插件并不只是滚动,还有其他应用,比如手机端联系人列表插件,我完全搞不懂这是怎么实现的,自然也使用不起来。最近我就用vue自己实现了一个手机端联系人列表,非常非常之简单,一个函数搞定,难点在于html的合理布局,所以没有发到这里,有兴趣的小伙伴可以去github看下。
    知其然,更要知其所以然。这样才能慢慢进步,否则只能靠搬运插件混生活了。

    源码

    https://github.com/yuyeqianxu...

    文章版权归作者所有,未经允许请勿转载,若此文章存在违规行为,您可以联系管理员删除。

    转载请注明本文地址:https://www.ucloud.cn/yun/92038.html

    相关文章

    • 回顾自己三次失败的面试经历

      摘要:站在这个时间点上,我对自己之前三次失败的面试经历做了一次深度回顾。关于我第三次面试失败的经历,依然是与轮播图有关。当然,这次思特奇面试之旅,最后也是以失败告终,这也是我离进大厂最近的一次。 showImg(https://segmentfault.com/img/bVYQuP?w=528&h=513); 前言 时间的齿轮已经来到了2017年的11月份,距离2018年仅仅还剩下不到两...

      DC_er 评论0 收藏0
    • 回顾自己三次失败的面试经历

      摘要:站在这个时间点上,我对自己之前三次失败的面试经历做了一次深度回顾。关于我第三次面试失败的经历,依然是与轮播图有关。当然,这次思特奇面试之旅,最后也是以失败告终,这也是我离进大厂最近的一次。 showImg(https://segmentfault.com/img/bVYQuP?w=528&h=513); 前言 时间的齿轮已经来到了2017年的11月份,距离2018年仅仅还剩下不到两...

      spacewander 评论0 收藏0
    • 写jquery插件【轮播图】历程

      摘要:轮播图插件的任务已经接近尾声,在书写轮播图期间确实有一些小的感触的。 轮播图插件的任务已经接近尾声,在书写轮播图期间确实有一些小的感触的。感兴趣的可以访问我的轮播图的线上地址:轮播图 首先,轮播图插件其实并不是我第一次写,之前也写过,不过那时候是按照别人的思路写下来的,算起来大概有一年了,这次又一次开始轮播图是因为拜读了《单页面Web应用 JavaScript从前端到后端》的这本书的1...

      khlbat 评论0 收藏0
    • 写jquery插件【轮播图】历程

      摘要:轮播图插件的任务已经接近尾声,在书写轮播图期间确实有一些小的感触的。 轮播图插件的任务已经接近尾声,在书写轮播图期间确实有一些小的感触的。感兴趣的可以访问我的轮播图的线上地址:轮播图 首先,轮播图插件其实并不是我第一次写,之前也写过,不过那时候是按照别人的思路写下来的,算起来大概有一年了,这次又一次开始轮播图是因为拜读了《单页面Web应用 JavaScript从前端到后端》的这本书的1...

      snowLu 评论0 收藏0

    发表评论

    0条评论

    最新活动
    阅读需要支付1元查看
    <