bootstrap在2.1新增的組件,直譯過來就是固定。其實這組件很簡單,就是通過添加或移除affix這個類名實現屏幕固定或不固定。當頁面加載完畢時,JS插件會搜索頁面上所有[data-spy="affix"]的元素,然后找其data-offset-top或data-offset-bottom屬性,即離頁面頂(底)部少於多少px,就放棄固定,平時你怎么滾動,被固定的元素都定在這個位置上不動。
此組件只要用戶為元素定義兩個屬性,引入JS與CSS就生效了。用戶基本不用寫碼。網上許多例子都是多此一舉!
此組件也沒有任何自定義事件!
!function ($) {
"use strict"; // jshint ;_;
/* AFFIX CLASS DEFINITION
* ====================== */
var Affix = function (element, options) {
this.options = $.extend({}, $.fn.affix.defaults, options)
this.$window = $(window)//只要是綁定事件
.on('scroll.affix.data-api', $.proxy(this.checkPosition, this))
.on('click.affix.data-api', $.proxy(function () {
setTimeout($.proxy(this.checkPosition, this), 1)
}, this))//當我們移動或點擊時自動進行修正
this.$element = $(element)
this.checkPosition()
}
Affix.prototype.checkPosition = function () {
if (!this.$element.is(':visible')) return
var scrollHeight = $(document).height()
, scrollTop = this.$window.scrollTop()
, position = this.$element.offset()
, offset = this.options.offset
, offsetBottom = offset.bottom
, offsetTop = offset.top
, reset = 'affix affix-top affix-bottom'
, affix
if (typeof offset != 'object') offsetBottom = offsetTop = offset
if (typeof offsetTop == 'function') offsetTop = offset.top()
if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()
//比較當前元素到頂部的距離與window.pageYOffset的差
//通過affix-top affix-bottom這兩個類名移除固定效果
affix = this.unpin != null && (scrollTop + this.unpin <= position.top) ?
false : offsetBottom != null && (position.top + this.$element.height() >= scrollHeight - offsetBottom) ?
'bottom' : offsetTop != null && scrollTop <= offsetTop ?
'top' : false
if (this.affixed === affix) return
this.affixed = affix
this.unpin = affix == 'bottom' ? position.top - scrollTop : null
this.$element.removeClass(reset).addClass('affix' + (affix ? '-' + affix : ''))
}
/* AFFIX PLUGIN DEFINITION
* ======================= */
var old = $.fn.affix
$.fn.affix = function (option) {
return this.each(function () {
var $this = $(this)
, data = $this.data('affix')
, options = typeof option == 'object' && option
if (!data) $this.data('affix', (data = new Affix(this, options)))
if (typeof option == 'string') data[option]()//這里是無效的,因為它只有一個checkPosition方法,而這方法會自動調用
})
}
$.fn.affix.Constructor = Affix
$.fn.affix.defaults = {
offset: 0
}
/* AFFIX NO CONFLICT
* ================= */
$.fn.affix.noConflict = function () {
$.fn.affix = old
return this
}
/* AFFIX DATA-API
* ============== */
$(window).on('load', function () {
//取得頁面上所有帶[data-spy="affix"]的元素,它此外還有個像data-offset-top=50 data-offset-bottom=10的屬性
$('[data-spy="affix"]').each(function () {
var $spy = $(this)
, data = $spy.data()
data.offset = data.offset || {}//在其緩存對象上開辟一個空間
//放入差值
data.offsetBottom && (data.offset.bottom = data.offsetBottom)
data.offsetTop && (data.offset.top = data.offsetTop)
$spy.affix(data)
})
})
}(window.jQuery);
