基于jQuery,所以必须在之前引入jQuery
* 插件功能:实现导航栏在滚动过程中的显示隐藏特效
* 传入参数为对象,包含4个属性:
* selector: 选择器 必须
* animate: 动画方式 可选
* time: 过渡时间 可选
* distance: 执行动画的距离 可选
* 选择器为必须传入的参数, 其余参数可选,其中动画方式可选"fade","slide"
* options = { selector, animate, time, distance }
/**
*
* navToggle 基于jQuery,所以必须在之前引入jQuery
* 插件功能:实现导航栏在滚动过程中的显示隐藏特效
*
* 传入参数为对象,包含4个属性:
* selector: 选择器 必须
* animate: 动画方式 可选
* time: 过渡时间 可选
* distance: 执行动画的距离 可选
*
* 选择器为必须传入的参数, 其余参数可选,其中动画方式可选"fade","slide"
* options = { selector, animate, time, distance }
*/
(function($){
//设置默认参数
var defaults = {
selector: "",
animate: "fade",
time: 500,
distance: 120
},
//设置动画种类,可扩展
animations = {
fade : ["fadeOut" ,"fadeIn" ],
slide: ["slideUp", "slideDown"]
};
$.extend({
// 创建isDom方法 判断jQuery对象转换dom对象是否合法
isDom: function(obj){
// 考虑兼容性 在chrome浏览器中 typeof HTMLElement === 'function'
if(typeof HTMLElement === 'object'){
return obj instanceof HTMLElement;
}
else {
return obj && typeof obj === 'object' && obj.nodeType === 1 && typeof obj.nodeName === 'string';
}
},
navToggle: function(options){
//检查用户设置的selector是否合法,强制设置该参数,如果不合法,抛出错误,结束进程
options = options || null;
if( !$.isDom($(options.selector)[0]) ){
throw new Error( "arguments[0] is not valid" );
}
var opts = $.extend( {}, defaults, options );
//选择动画种类
var animate = (opts.animate === "fade") ? animations.fade : animations.slide;
$.each( $(opts.selector), function(){
var $this = $(this),
distance = opts.distance,
_winTop = 0;
$(window).on('scroll', function(){
var winTop = $(this).scrollTop();
// 下滑
if (winTop > _winTop ) {
if(winTop >= distance){
// 执行动画之前必须先清除所有的事件队列 stop()
$this.stop()[ animate[0] ](opts.time);
}
}
// 上滑
else {
$this.stop()[ animate[1] ](opts.time);
}
_winTop = $(this).scrollTop();
})
});
}
});
})(window.jQuery);