自己遇到业务的时候可以自己封装一个插件!
//==1.前面加入分号,用()包裹
;(function($, window, document, undefined){
//==2 pluginName
var pluginName = "navScrollSpy";
//==3 defaults options
var defaults = {
navContainer: '#nav', //外部容器
navItems: 'a' //元素
};
//==4.定义私有对象
function navScrollSpy(element, options){
this.element = element; //获得id=#nav
this.$ele = $(element); //获得$("#nav")
this.$win = $(window); //获取window
//==5.拓展对象
this.options = $.extend({}, defaults, options); //得到参数值
this._defaults = defaults;
this._name = pluginName;
this.boxs = {}; //定义一个对象用来存放box的top值
this.init();
};
//==5.为原型添加方法
navScrollSpy.prototype = {
init: function(){
//得到a元素
this.$a = this.$ele.find(this.options.navItems);
//得到内容区Box的top值
this.getBoxTop();
//点击切换导航按钮样式,更改上下文this
this.$a.on("click", $.proxy(this.clickSwitch,this));
//滚动切换导航按钮
this.$win.on("scroll",$.proxy(this.scrolling,this));
//当页面重置时会发生问题?
return this;
},
//导航固定
fixNav: function(){
var st = $(window).scrollTop();
var $nav = $(this.options.navContainer)
var fixValue = this.options.oldTop;
if(st >= fixValue){
$nav.css({
"position":"fixed",
"top" : this.options.newTop+"px"
});
}else{
$nav.css({
"position":"absolute",
"top" : fixValue+"px"
});
}
}
};
//==6.拓展方法
$.fn.navScrollSpy = function(options){
return this.each(function(){
if(!$.data(this, "plugin_"+pluginName)){
$.data(this, "plugin_"+pluginName,new navScrollSpy(this, options));
}
});
};
})(jQuery, window, document);