Skip to content

Instantly share code, notes, and snippets.

@shepherdwind
Created June 4, 2012 07:42
Show Gist options
  • Save shepherdwind/2867000 to your computer and use it in GitHub Desktop.
Save shepherdwind/2867000 to your computer and use it in GitHub Desktop.
scroll follow
/**
* Created by [email protected].
* Date: 2012-06-04
* Time: 13:40
* Desc: 自动跟随
*/
KISSY.add('market/scrollFollow', function(S){
var D = S.DOM;
var E = S.Event;
/**
* 滚动函数出发时间间隔,默认情况下,ie6 50ms,其他浏览器10ms
*/
var FLUSH_TIME = S.UA.ie === 6 ? 50: 10;
var cfg = {
/**
* 跟随的元素选择器或者dom
*/
followEl: '',
/**
* 是否更新高度,有时候高度是变化的,需要每次重新计算高度
*/
fixTop: false
};
/**
* 构造器,ScrollFollow,高度自动跟随
* @class ScrollFollow
* @example:
* new ScrollFollow('#J_id');
* new ScrollFollow({followEl: '#J_id .class', fixTop: true});
*/
function ScrollFollow(conf){
conf = conf || {};
if (S.isString(conf)){
this.followEl = conf;
} else {
S.each(cfg, function(val, attr){
this[attr] = conf[attr] || val;
}, this);
}
this.init();
}
ScrollFollow.prototype = {
constructor: ScrollFollow,
init: function(){
this.followEl = S.one(this.followEl);
if (!this.followEl) return;
if (!this.top) this.top = this.followEl.offset().top;
this.cssPosition = this.followEl.css('position');
this.cssWidth = this.followEl.css('width');
this.hander = {};
this._bind();
},
_bind: function(){
E.on(window, "scroll", function(){
var hander = this.hander;
hander.cancel && hander.cancel();
this.hander = S.later(this.resetPosition, FLUSH_TIME, false, this);
}, this);
},
resetPosition: function(){
var winTop = parseInt(D.scrollTop(window), 10);
var followEl = this.followEl;
var top = +this.top;
if (winTop > top){
this.fixIt(winTop);
} else if(winTop < top && this.status !== 'auto') {
followEl.css({
position: this.cssPosition,
top: top,
width: ''
});
//如果高度需要修复
if (this.fixTop) this.top = followEl.offset().top;
this.status = 'auto';
}
},
fixIt: function(winTop){
var followEl = this.followEl;
var top = this.top;
if (S.UA.ie === 6){
followEl.css({
position: 'absolute',
top: winTop,
width: this.cssWidth
});
} else if(this.status !== 'follow'){
followEl.css({
position: 'fixed',
top: 0,
width: this.cssWidth
});
}
this.status = 'follow';
}
};
return ScrollFollow;
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment