bootstrap之 carousel.js輪播外掛原始碼分析
阿新 • • 發佈:2019-02-14
公司主要客戶是外國人,主要交流語言是英語,公司裡的人都使用一口流利的中國式英語進行對話,中國式英語在不正式場合沒什麼問題,大家都聽得懂即可。可惜,我不會,所以接下來得好好練習英語口語了。相信我能夠堅持下來,起碼把中國式英語學會。
以前都是jQuery或者zepto(移動端)佈局完事,後來公司要求pc端移動端相容,然後想到bootstrap,當然,公司專案很小,小外包公司嘛。所以瀏覽器相容跟隨bootstrap新版本走,不支援css3的全部沒戲。
軟體行業都有外包公司技術深度不夠(就是菜)說法,作為小外包公司,深有體會。但我想改變現狀,所以打起原始碼主意,其實研究好的原始碼,會學到很多知識。
今天來研究下 carousel.js輪播外掛原始碼,依然會是簡單的原始碼解讀,大神繞道。
/* ======================================================================== * Bootstrap: carousel.js v3.3.7 * http://getbootstrap.com/javascript/#carousel * ======================================================================== * Copyright 2011-2016 Twitter, Inc. * Licensed under MIT (https://github.com/twbs/bootstrap/blob/master/LICENSE) * ======================================================================== */ +function ($) { 'use strict';//嚴格模式,能夠限制一些js程式碼弊端,糟粕,為新js標準鋪路 // CAROUSEL CLASS DEFINITION // ========================= //Carousel類建構函式 var Carousel = function (element, options) { this.$element = $(element)//選擇Dom元素 this.$indicators = this.$element.find('.carousel-indicators')//找到含有carousel-indicators類名的元素(輪播切換下標) this.options = options//選項 this.paused = null //暫停切換 this.sliding = null //滑動 this.interval = null //每個輪播圖切換時間間隔 this.$active = null //活動圖片標示(展示那張輪播圖) this.$items = null //圖片數量 this.options.keyboard && this.$element.on('keydown.bs.carousel', $.proxy(this.keydown, this)) this.options.pause == 'hover' && !('ontouchstart' in document.documentElement) && this.$element .on('mouseenter.bs.carousel', $.proxy(this.pause, this)) .on('mouseleave.bs.carousel', $.proxy(this.cycle, this)) } Carousel.VERSION = '3.3.7'//Carousel外掛版本號,跟隨bootstrap版本號 Carousel.TRANSITION_DURATION = 600 //圖片過渡時間600ms //外掛預設圖片切換時間5000ms,滑鼠經過暫停,連續播放,按鍵(滑鼠左鍵)控制true Carousel.DEFAULTS = { interval: 5000, pause: 'hover', wrap: true, keyboard: true } //左右按鍵切換輪播圖 Carousel.prototype.keydown = function (e) { //正則驗證事件目標名字是否含有input或者textarea(忽略大小寫)有就返回 //也就是說滑鼠要點選到左右切換按鈕(a標籤)才能夠使用左右按鍵控制切換,點選輪播圖,input控制元件,文字區域都不行 if (/input|textarea/i.test(e.target.tagName)) return switch (e.which) { case 37: this.prev(); break case 39: this.next(); break default: return } //阻止事件冒泡 e.preventDefault() } //輪播圖迴圈播放控制 Carousel.prototype.cycle = function (e) { e || (this.paused = false) //類似於if(e||(this.paused = false)){} this.interval && clearInterval(this.interval)//如果this.interval為true,則清空計時器 //if(this.options.interval&&!this.paused){this.interval = setInterval($.proxy(this.next, this), this.options.interval)} //bootstrap外掛中用來代替if else慣用技巧 this.options.interval && !this.paused && (this.interval = setInterval($.proxy(this.next, this), this.options.interval)) return this //返回this } //得到當前活躍的圖片下標 Carousel.prototype.getItemIndex = function (item) { this.$items = item.parent().children('.item') return this.$items.index(item || this.$active) } //滑動方向控制 Carousel.prototype.getItemForDirection = function (direction, active) { var activeIndex = this.getItemIndex(active) var willWrap = (direction == 'prev' && activeIndex === 0) || (direction == 'next' && activeIndex == (this.$items.length - 1)) if (willWrap && !this.options.wrap) return active var delta = direction == 'prev' ? -1 : 1 var itemIndex = (activeIndex + delta) % this.$items.length return this.$items.eq(itemIndex) } //切換到目標圖片 Carousel.prototype.to = function (pos) { var that = this var activeIndex = this.getItemIndex(this.$active = this.$element.find('.item.active')) if (pos > (this.$items.length - 1) || pos < 0) return if (this.sliding) return this.$element.one('slid.bs.carousel', function () { that.to(pos) }) // yes, "slid" if (activeIndex == pos) return this.pause().cycle() return this.slide(pos > activeIndex ? 'next' : 'prev', this.$items.eq(pos)) } //暫停滑動 Carousel.prototype.pause = function (e) { e || (this.paused = true) if (this.$element.find('.next, .prev').length && $.support.transition) { this.$element.trigger($.support.transition.end) this.cycle(true) } this.interval = clearInterval(this.interval) return this } //下一張圖片 Carousel.prototype.next = function () { if (this.sliding) return return this.slide('next') } //上一張圖片 Carousel.prototype.prev = function () { if (this.sliding) return return this.slide('prev') } //輪播切換具體實現,新增active 下一張圖片滑動方向,滑鼠暫停等等 Carousel.prototype.slide = function (type, next) { var $active = this.$element.find('.item.active') var $next = next || this.getItemForDirection(type, $active) var isCycling = this.interval var direction = type == 'next' ? 'left' : 'right' var that = this if ($next.hasClass('active')) return (this.sliding = false) var relatedTarget = $next[0] var slideEvent = $.Event('slide.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) this.$element.trigger(slideEvent) if (slideEvent.isDefaultPrevented()) return this.sliding = true isCycling && this.pause() if (this.$indicators.length) { this.$indicators.find('.active').removeClass('active') var $nextIndicator = $(this.$indicators.children()[this.getItemIndex($next)]) $nextIndicator && $nextIndicator.addClass('active') } var slidEvent = $.Event('slid.bs.carousel', { relatedTarget: relatedTarget, direction: direction }) // yes, "slid" if ($.support.transition && this.$element.hasClass('slide')) { $next.addClass(type) $next[0].offsetWidth // force reflow $active.addClass(direction) $next.addClass(direction) $active .one('bsTransitionEnd', function () { $next.removeClass([type, direction].join(' ')).addClass('active') $active.removeClass(['active', direction].join(' ')) that.sliding = false setTimeout(function () { that.$element.trigger(slidEvent) }, 0) }) .emulateTransitionEnd(Carousel.TRANSITION_DURATION) } else { $active.removeClass('active') $next.addClass('active') this.sliding = false this.$element.trigger(slidEvent) } isCycling && this.cycle() return this } // CAROUSEL PLUGIN DEFINITION // ========================== //Carousel外掛定義 function Plugin(option) { return this.each(function () { var $this = $(this) var data = $this.data('bs.carousel') var options = $.extend({}, Carousel.DEFAULTS, $this.data(), typeof option == 'object' && option) var action = typeof option == 'string' ? option : options.slide if (!data) $this.data('bs.carousel', (data = new Carousel(this, options))) if (typeof option == 'number') data.to(option) else if (action) data[action]() else if (options.interval) data.pause().cycle() }) } var old = $.fn.carousel $.fn.carousel = Plugin $.fn.carousel.Constructor = Carousel // CAROUSEL NO CONFLICT // ==================== //防止衝突noConflict,目的是釋放$控制權 $.fn.carousel.noConflict = function () { $.fn.carousel = old return this } // CAROUSEL DATA-API // ================= //點選控制代碼繫結 var clickHandler = function (e) { var href var $this = $(this) var $target = $($this.attr('data-target') || (href = $this.attr('href')) && href.replace(/.*(?=#[^\s]+$)/, '')) // strip for ie7 if (!$target.hasClass('carousel')) return var options = $.extend({}, $target.data(), $this.data()) var slideIndex = $this.attr('data-slide-to') if (slideIndex) options.interval = false Plugin.call($target, options) if (slideIndex) { $target.data('bs.carousel').to(slideIndex) } e.preventDefault() } $(document) .on('click.bs.carousel.data-api', '[data-slide]', clickHandler) .on('click.bs.carousel.data-api', '[data-slide-to]', clickHandler) $(window).on('load', function () { $('[data-ride="carousel"]').each(function () { var $carousel = $(this) Plugin.call($carousel, $carousel.data()) }) }) }(jQuery);
由於時間以及個人技術問題,有些具體的來不及寫註釋,放到有空再來修改編輯了。目前先這樣,晚安!