首页 > bootstrap affix问题

bootstrap affix问题

想实现一个效果,滚动页面一段距离后,页面右下角出现工具条(包含滚动到顶部),当滚动到最底部快接触到footer时,工具条的位置又刚好偏移到footer区域上方

用bootstrap affix勉强实现了下,发现这个插件有问题

实现效果 http://fiddle.jshell.net/deathfang/Z3e75/show/

失败情况 http://fiddle.jshell.net/deathfang/PCdp8/show/

根据affix.js http://twbs.github.io/bootstrap/js/affix.js 源码,

Affix.prototype.checkPosition = function () {
    if (!this.$element.is(':visible')) return

    var scrollHeight = $(document).height()
    var scrollTop    = this.$window.scrollTop()
    var position     = this.$element.offset()
    var offset       = this.options.offset
    var offsetTop    = offset.top
    var offsetBottom = offset.bottom

    if (typeof offset != 'object')         offsetBottom = offsetTop = offset
    if (typeof offsetTop == 'function')    offsetTop    = offset.top()
    if (typeof offsetBottom == 'function') offsetBottom = offset.bottom()

    var 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
    if (this.unpin) this.$element.css('top', '')

    this.affixed = affix
    this.unpin   = affix == 'bottom' ? position.top - scrollTop : null

    this.$element.removeClass(Affix.RESET).addClass('affix' + (affix ? '-' + affix : ''))

    if (affix == 'bottom') {
      this.$element.offset({ top: scrollHeight - offsetBottom - this.$element.height() })
    }
  }

失败的例子原因是

position.top + this.$element.height() >= scrollHeight - offsetBottom 

position.top就是 $element初始的位置,第一个实现效果我就把 $element放到DOM结构比较靠前的位置让页面初次加载时 这条判断不成立,之后affix affix-bottom这2个class就可以正常切换
不过这样解决就不语义化了,请教更好的实现方案

【热门文章】
【热门文章】