JavaScript吸顶灯的实现

吸顶灯是各站点常用的一个功能,它有两个特性

  1. 向下滚动到div位置时,该div一直固定在页面的顶部
  2. 向上滚动到div原有位置时,div又恢复到文档中的原位置

 

div可能是一个“分类菜单,也可能是一个“文章导航。如

也有可能是一个购物 “账单信息

 

实现思路如下

  1. div初始居普通文档流中
  2. 给window添加scroll事件(可事件节流),获取div的offset的top值,滚动时scrollTop值和top比较,当到达top时给div添加一个fixed的class使其固定
  3. 向上滚动时当到达div初始top时则删除fixed的class,此时div又回到普通文档流中
  4. fixed样式非IE6浏览器使用position:fixed,IE6使用position:absolute和IE expression
.fixed {
    position: fixed;
    top: 0;
    z-index: 100;
    -position: absolute;
    -top: expression(eval(document.documentElement.scrollTop))
}

  

jQuery插件的实现代码如下

/*
 * 吸顶灯
 * option {
 *    fixCls: className,默认 “fixed”
 *    fixedFunc: 吸顶时回调函数
 *    resetFunc: 不吸顶时回调函数
 * }
 */
$.fn.topSuction = function(option) {
    option = option || {}
    var fixCls = option.fixCls || 'fixed'
    var fixedFunc = option.fixedFunc
    var resetFunc = option.resetFunc

    var $self = this
    var $win  = $(window)
    if (!$self.length) return

    var offset = $self.offset()
    var fTop   = offset.top
    var fLeft  = offset.left

    // 暂存
    $self.data('def', offset)
    $win.resize(function() {
        $self.data('def', $self.offset())
    })

    $win.scroll(function() {
        var dTop = $(document).scrollTop()
        if (fTop < dTop) {
            $self.addClass(fixCls)
            if (fixedFunc) {
                fixedFunc.call($self, fTop)
            }
        } else {
            $self.removeClass(fixCls)
            if (resetFunc) {
                resetFunc.call($self, fTop)
            }
        }
    })
};

这里分别提供了两个回调,fixedFunc在fixed后调用,resetFunc在恢复到初始状态时调用。

 

线上示例

posted on 2014-10-08 14:29  snandy  阅读(8347)  评论(12编辑  收藏  举报