国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > JavaScript > 正文

BootStrap Tooltip插件源碼解析

2019-11-19 18:14:09
字體:
來源:轉載
供稿:網友

Tooltip插件可以讓你把要顯示的內容以彈出框的形式來展示,如:

因為自己在工作的過程中,用到了Tooltip這個插件,并且當時正想學習一下元素定位的問題,如:提示框顯示的位置就是觸發提示框元素的位置,可以配置在上、下、左、右等位置,所以就去看了源碼。對于整個插件源碼沒有看全,但也學到了許多的知識點。能力有限,可能其中有認識錯誤的地方,以后再補充吧

1 使用方法不介紹 ,可以參照

Bootstrap 提示工具(Tooltip)插件

2 源碼解析

+function ($) { 'use strict'; // TOOLTIP PUBLIC CLASS DEFINITION // =============================== var Tooltip = function (element, options) {  this.type    =  this.options  =  this.enabled  =  this.timeout  =  this.hoverState =  this.$element  = null  this.init('tooltip', element, options) } Tooltip.VERSION = '3.3.0' Tooltip.TRANSITION_DURATION = 150 //默認參數 Tooltip.DEFAULTS = {  animation: true,  placement: 'top',  selector: false,  template: '<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div>',  trigger: 'hover focus',  title: '',  delay: 0,  html: false,  container: false,  viewport: {   selector: 'body',   padding: 0  } } //初始化 Tooltip.prototype.init = function (type, element, options) {  this.enabled  = true  this.type   = type  this.$element = $(element)  //初始化參數  this.options  = this.getOptions(options)  this.$viewport = this.options.viewport && $(this.options.viewport.selector || this.options.viewport)  //多個觸發器 即觸發函數  var triggers = this.options.trigger.split(' ')  for (var i = triggers.length; i--;) {   var trigger = triggers[i]   if (trigger == 'click') {    //綁定事件處理程序    //事件命名空間 'click.tooltip'    //觸發時執行$.proxy(this.toggle, this)返回的函數    this.$element.on('click.' + this.type, this.options.selector, $.proxy(this.toggle, this))   } else if (trigger != 'manual') {    var eventIn = trigger == 'hover' ? 'mouseenter' : 'focusin'    var eventOut = trigger == 'hover' ? 'mouseleave' : 'focusout'    this.$element.on(eventIn + '.' + this.type, this.options.selector, $.proxy(this.enter, this))    this.$element.on(eventOut + '.' + this.type, this.options.selector, $.proxy(this.leave, this))   }  }  this.options.selector ?   (this._options = $.extend({}, this.options, { trigger: 'manual', selector: '' })) :   this.fixTitle() } Tooltip.prototype.getDefaults = function () {  return Tooltip.DEFAULTS } //獲得初始化參數 Tooltip.prototype.getOptions = function (options) {  // this.$element.data() data-key = value 形式的屬性獲取   // 返回一個對象{key:value}  // options > 元素屬性 > 默認   options = $.extend({}, this.getDefaults(), this.$element.data(), options)  //delay 為數字 特殊處理  //delay 為對象 delay:{ show: 500, hide: 100 }  if (options.delay && typeof options.delay == 'number') {   options.delay = {    show: options.delay,    hide: options.delay   }  }  return options } Tooltip.prototype.getDelegateOptions = function () {  var options = {}  var defaults = this.getDefaults()  this._options && $.each(this._options, function (key, value) {   if (defaults[key] != value) options[key] = value  })  return options } //提示框顯示 Tooltip.prototype.enter = function (obj) {  //obj是否是tooltip的實例  var self = obj instanceof this.constructor ?   obj : $(obj.currentTarget).data('bs.' + this.type)  //$tip.is(':visible') 該div是否可見  //可見時 只更新狀態 然后直接返回  if (self && self.$tip && self.$tip.is(':visible')) {   self.hoverState = 'in'   return  }  //self 不存在  if (!self) {   self = new this.constructor(obj.currentTarget, this.getDelegateOptions())   $(obj.currentTarget).data('bs.' + this.type, self)  }  //上次點擊延時未顯示 則取消顯示  clearTimeout(self.timeout)  //設置狀態  self.hoverState = 'in'  //delay: 數字 (默認 0) 或  對象 { show: 500, hide: 100 }  //沒有delay delay.show 時 直接顯示   if (!self.options.delay || !self.options.delay.show) return self.show()  //延時顯示 self.options.delay.show:延時時間  self.timeout = setTimeout(function () {   if (self.hoverState == 'in') self.show()  }, self.options.delay.show) } //提示框隱藏 Tooltip.prototype.leave = function (obj) {  var self = obj instanceof this.constructor ?   obj : $(obj.currentTarget).data('bs.' + this.type)  if (!self) {   self = new this.constructor(obj.currentTarget, this.getDelegateOptions())   $(obj.currentTarget).data('bs.' + this.type, self)  }  clearTimeout(self.timeout)  self.hoverState = 'out'  if (!self.options.delay || !self.options.delay.hide) return self.hide()  self.timeout = setTimeout(function () {   if (self.hoverState == 'out') self.hide()  }, self.options.delay.hide) } //提示框顯示核心方法 Tooltip.prototype.show = function () {  console.info(this)   var e = $.Event('show.bs.' + this.type)  if (this.hasContent() && this.enabled) {   this.$element.trigger(e)   //判斷是否在根節點中   //this.$element[0] 轉換為DOM對象   //.ownerDocument Document文檔對象   //.documentElement 根節點 HTML標簽   //$.contains 一個DOM節點是否包含另一個DOM節點。   var inDom = $.contains(this.$element[0].ownerDocument.documentElement, this.$element[0])   //調用preventDefault 或 不在根節點 return   //事件對象中是否調用過 event.preventDefault()   //event.preventDefault():阻止元素發生默認的行為   //如 當點擊提交按鈕時阻止對表單的提交 、 阻止以下 URL 的鏈接   if (e.isDefaultPrevented() || !inDom) return   var that = this   var $tip = this.tip()   var tipId = this.getUID(this.type)   //設置提示框的title   this.setContent()   $tip.attr('id', tipId)   this.$element.attr('aria-describedby', tipId)   //參數animation   if (this.options.animation) $tip.addClass('fade')   //參數placement 提示框的位置 top bottom left right   var placement = typeof this.options.placement == 'function' ?    this.options.placement.call(this, $tip[0], this.$element[0]) :    this.options.placement   // 判斷placement是否包含"auto"   var autoToken = //s?auto?/s?/i   var autoPlace = autoToken.test(placement)   //包含 "auto"時   if (autoPlace) placement = placement.replace(autoToken, '') || 'top'   $tip    //detach() 刪除匹配的對象 與remove()不同的是,所有綁定的事件、附加的數據等都會保留下來    .detach()    .css({ top: 0, left: 0, display: 'block' })    .addClass(placement)    .data('bs.' + this.type, this)   //參數 container 向指定元素添加該提示框   //沒有 添加到當前元素后面   this.options.container ? $tip.appendTo(this.options.container) : $tip.insertAfter(this.$element)   //位置對象pos pos = {top: , right: , bottom: , left: , width: ,scroll:}   var pos     = this.getPosition()   //提示框自身實際的 width height   var actualWidth = $tip[0].offsetWidth   var actualHeight = $tip[0].offsetHeight   if (autoPlace) {    var orgPlacement = placement    var $container  = this.options.container ? $(this.options.container) : this.$element.parent()    var containerDim = this.getPosition($container)    placement = placement == 'bottom' && pos.bottom + actualHeight > containerDim.bottom ? 'top'  :          placement == 'top'  && pos.top  - actualHeight < containerDim.top  ? 'bottom' :          placement == 'right' && pos.right + actualWidth > containerDim.width ? 'left'  :          placement == 'left'  && pos.left  - actualWidth < containerDim.left  ? 'right' :          placement    $tip     .removeClass(orgPlacement)     .addClass(placement)   }   //計算提示框的偏移量 {top: , left: }   var calculatedOffset = this.getCalculatedOffset(placement, pos, actualWidth, actualHeight)   //應用并設置偏移量   this.applyPlacement(calculatedOffset, placement)   var complete = function () {    var prevHoverState = that.hoverState    that.$element.trigger('shown.bs.' + that.type)    that.hoverState = null    if (prevHoverState == 'out') that.leave(that)   }   $.support.transition && this.$tip.hasClass('fade') ?    $tip     .one('bsTransitionEnd', complete)     .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :    complete()  } } Tooltip.prototype.applyPlacement = function (offset, placement) {  var $tip  = this.tip()  var width = $tip[0].offsetWidth  var height = $tip[0].offsetHeight  // manually read margins because getBoundingClientRect includes difference  //獲得提示框自身的外邊距的值  var marginTop = parseInt($tip.css('margin-top'), 10)  var marginLeft = parseInt($tip.css('margin-left'), 10)  // we must check for NaN for ie 8/9  //是否是非數字  if (isNaN(marginTop)) marginTop = 0  if (isNaN(marginLeft)) marginLeft = 0  //計算的偏移量 + 自身的外邊距  offset.top = offset.top + marginTop  offset.left = offset.left + marginLeft  // $.fn.offset doesn't round pixel values  // so we use setOffset directly with our own function B-0  // 應用了offset.setOffset方法,傳入了using參數,因為offset設置值的時候,不能四舍五入  $.offset.setOffset($tip[0], $.extend({   using: function (props) {    $tip.css({     top: Math.round(props.top),     left: Math.round(props.left)    })   }  }, offset), 0)  //添加 in class 讓提示框顯示  $tip.addClass('in')  // check to see if placing tip in new offset caused the tip to resize itself  //獲取顯示后的提示框的寬和高 檢查是否調整了自身的大小  var actualWidth = $tip[0].offsetWidth  var actualHeight = $tip[0].offsetHeight  if (placement == 'top' && actualHeight != height) {   offset.top = offset.top + height - actualHeight  }  var delta = this.getViewportAdjustedDelta(placement, offset, actualWidth, actualHeight)  if (delta.left) offset.left += delta.left  else offset.top += delta.top  var isVertical     = /top|bottom/.test(placement)  var arrowDelta     = isVertical ? delta.left * 2 - width + actualWidth : delta.top * 2 - height + actualHeight  var arrowOffsetPosition = isVertical ? 'offsetWidth' : 'offsetHeight'  $tip.offset(offset)  this.replaceArrow(arrowDelta, $tip[0][arrowOffsetPosition], isVertical) } Tooltip.prototype.replaceArrow = function (delta, dimension, isHorizontal) {  this.arrow()   .css(isHorizontal ? 'left' : 'top', 50 * (1 - delta / dimension) + '%')   .css(isHorizontal ? 'top' : 'left', '') } //設置提示框的title Tooltip.prototype.setContent = function () {  //div  var $tip = this.tip()  var title = this.getTitle()  $tip.find('.tooltip-inner')[this.options.html ? 'html' : 'text'](title)  $tip.removeClass('fade in top bottom left right') } Tooltip.prototype.hide = function (callback) {  var that = this  var $tip = this.tip()  var e  = $.Event('hide.bs.' + this.type)  function complete() {   if (that.hoverState != 'in') $tip.detach()   that.$element    .removeAttr('aria-describedby')    .trigger('hidden.bs.' + that.type)   callback && callback()  }  this.$element.trigger(e)  if (e.isDefaultPrevented()) return  $tip.removeClass('in')  $.support.transition && this.$tip.hasClass('fade') ?   $tip    .one('bsTransitionEnd', complete)    .emulateTransitionEnd(Tooltip.TRANSITION_DURATION) :   complete()  this.hoverState = null  return this } Tooltip.prototype.fixTitle = function () {  var $e = this.$element  if ($e.attr('title') || typeof ($e.attr('data-original-title')) != 'string') {   $e.attr('data-original-title', $e.attr('title') || '').attr('title', '')  } } Tooltip.prototype.hasContent = function () {  return this.getTitle() } //獲取位置 Tooltip.prototype.getPosition = function ($element) {  //不傳入 則為當前點擊元素  $element  = $element || this.$element  //轉換為DOM對象  var el   = $element[0]  //是否是body元素  var isBody = el.tagName == 'BODY'  //獲取元素各邊與頁面上邊和左邊的距離 left right top bottom height width  var elRect  = el.getBoundingClientRect()  //兼容IE8 沒有 width height 則計算  if (elRect.width == null) {   // width and height are missing in IE8, so compute them manually; see https://github.com/twbs/bootstrap/issues/14093   elRect = $.extend({}, elRect, { width: elRect.right - elRect.left, height: elRect.bottom - elRect.top })  }  //當前元素相對于文檔的偏移量  var elOffset = isBody ? { top: 0, left: 0 } : $element.offset()  //垂直滾動條的距離  //document.documentElement.scrollTop 和 document.body.scrollTop 瀏覽器兼容   var scroll  = { scroll: isBody ? document.documentElement.scrollTop || document.body.scrollTop : $element.scrollTop() }  var outerDims = isBody ? { width: $(window).width(), height: $(window).height() } : null  //合并   return $.extend({}, elRect, scroll, outerDims, elOffset) } //計算偏移量 Tooltip.prototype.getCalculatedOffset = function (placement, pos, actualWidth, actualHeight) {  return placement == 'bottom' ? { top: pos.top + pos.height,  left: pos.left + pos.width / 2 - actualWidth / 2 } :      placement == 'top'  ? { top: pos.top - actualHeight, left: pos.left + pos.width / 2 - actualWidth / 2 } :      placement == 'left'  ? { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left - actualWidth } :    /* placement == 'right' */ { top: pos.top + pos.height / 2 - actualHeight / 2, left: pos.left + pos.width  } } Tooltip.prototype.getViewportAdjustedDelta = function (placement, pos, actualWidth, actualHeight) {  var delta = { top: 0, left: 0 }  //默認參數  //viewport: {  // selector: 'body',  // padding: 0  //}  //默認的話 this.$viewport = 'body'  if (!this.$viewport) return delta  var viewportPadding = this.options.viewport && this.options.viewport.padding || 0  //this.$viewport = 'body' width height為 window的  var viewportDimensions = this.getPosition(this.$viewport)  console.info(viewportDimensions)  if (/right|left/.test(placement)) {   var topEdgeOffset  = pos.top - viewportPadding - viewportDimensions.scroll   var bottomEdgeOffset = pos.top + viewportPadding - viewportDimensions.scroll + actualHeight   if (topEdgeOffset < viewportDimensions.top) { // top overflow    delta.top = viewportDimensions.top - topEdgeOffset   } else if (bottomEdgeOffset > viewportDimensions.top + viewportDimensions.height) { // bottom overflow    delta.top = viewportDimensions.top + viewportDimensions.height - bottomEdgeOffset   }  } else {   var leftEdgeOffset = pos.left - viewportPadding   var rightEdgeOffset = pos.left + viewportPadding + actualWidth   if (leftEdgeOffset < viewportDimensions.left) { // left overflow    delta.left = viewportDimensions.left - leftEdgeOffset   } else if (rightEdgeOffset > viewportDimensions.width) { // right overflow    delta.left = viewportDimensions.left + viewportDimensions.width - rightEdgeOffset   }  }  return delta } //提示框的title Tooltip.prototype.getTitle = function () {  var title  var $e = this.$element  var o = this.options  //先獲取當前元素的data-original-title屬性  //否則獲取參數title  title = $e.attr('data-original-title')   || (typeof o.title == 'function' ? o.title.call($e[0]) : o.title)  return title } //隨機生成唯一id 0 -- 100000 id值   Tooltip.prototype.getUID = function (prefix) {  //~~ 去掉小數部分  do prefix += ~~(Math.random() * 1000000)  while (document.getElementById(prefix))  return prefix } //生成提示框的div //不存在 則用模板 //<div class="tooltip" role="tooltip"><div class="tooltip-arrow"></div><div class="tooltip-inner"></div></div> Tooltip.prototype.tip = function () {  return (this.$tip = this.$tip || $(this.options.template)) } Tooltip.prototype.arrow = function () {  return (this.$arrow = this.$arrow || this.tip().find('.tooltip-arrow')) } Tooltip.prototype.enable = function () {  this.enabled = true } Tooltip.prototype.disable = function () {  this.enabled = false } Tooltip.prototype.toggleEnabled = function () {  this.enabled = !this.enabled } //click 事件觸發時執行的函數 Tooltip.prototype.toggle = function (e) {  //this tooltip實例對象  var self = this  if (e) {   //e.currentTarget 返回注冊該事件處理程序的元素   self = $(e.currentTarget).data('bs.' + this.type)   if (!self) {    self = new this.constructor(e.currentTarget, this.getDelegateOptions())    $(e.currentTarget).data('bs.' + this.type, self)   }  }  //判斷提示框當前的狀態  //true 當前顯示 需要隱藏  //false 相反  self.tip().hasClass('in') ? self.leave(self) : self.enter(self) } Tooltip.prototype.destroy = function () {  var that = this  clearTimeout(this.timeout)  this.hide(function () {   that.$element.off('.' + that.type).removeData('bs.' + that.type)  }) } // TOOLTIP PLUGIN DEFINITION // ========================= function Plugin(option) {  return this.each(function () {   var $this  = $(this)   //所選元素是否有 key為:bs.tooltip 對應的value值   var data   = $this.data('bs.tooltip')   //option為對象 options:option   //option為字符串 則是方法 options:false    var options = typeof option == 'object' && option   //option是對象 執行初始化 ,并提供了選擇器   var selector = options && options.selector   //是destroy 方法 不執行   if (!data && option == 'destroy') return   //tooltip初始化   if (selector) {    //存在選擇器,則將當前點擊元素 bs.tooltip = {} 即去掉Tooltip實例    if (!data) $this.data('bs.tooltip', (data = {}))    //給選擇器加上Tooltip實例    if (!data[selector]) data[selector] = new Tooltip(this, options)   } else {    //沒有value值時,則加上 bs.tooltip = data(new Tooltip(this, options))     if (!data) $this.data('bs.tooltip', (data = new Tooltip(this, options)))   }   //執行方法   if (typeof option == 'string') data[option]()  }) } //緩存以前$.fn上的tooltip var old = $.fn.tooltip //添加到jQuery對象上 $.fn.tooltip       = Plugin $.fn.tooltip.Constructor = Tooltip // TOOLTIP NO CONFLICT // =================== //tooltip沖突時 調用該方法 //var other = $("#aa").tooltip().noConflict(); $.fn.tooltip.noConflict = function () {  $.fn.tooltip = old  return this }}(jQuery);

以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。

發表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發表
主站蜘蛛池模板: 米林县| 阿拉善左旗| 淮阳县| 英吉沙县| 济阳县| 临海市| 新余市| 友谊县| 武夷山市| 炉霍县| 西城区| 梨树县| 民乐县| 晋州市| 边坝县| 安达市| 凌源市| 那坡县| 扬中市| 云龙县| 百色市| 中方县| 芒康县| 石台县| 南充市| 阜城县| 呼伦贝尔市| 延吉市| 天长市| 宁津县| 崇仁县| 醴陵市| 胶南市| 板桥市| 赤水市| 喀喇沁旗| 陆良县| 五家渠市| 福鼎市| 怀仁县| 兰溪市|