对我来说,需要一些关于如何正确编写 jquery 插件的提示。
我从JQuery官网http://learn.jquery.com/plugins/basic-plugin-creation/开始研究这个问题
并且我决定自己写一个sticky header插件(我知道网上到处都是各种例子,我只需要写函数的技巧)
所以。我写了一个可以正常工作的简单函数。
function stickynav(el) {
$(window).scroll(function () {
if ( $(window).scrollTop() > 0 ) {
$(el).css({position: 'fixed', top: '0px'});
$(el).stop().animate({height : '40px',lineHeight : '40px'}, 200);
} else {
$(el).css({position: 'static'});
$(el).stop().animate({height : '80px',lineHeight : '80px'}, 200);
}
});
stickynav('nav');
在我决定尝试编写相同的函数之后,但在 JQuery 团队的建议下。
(function($){
$.fn.stickynav = function(options){
settings = $.extend({
topSpacing: 0,
initialHeight: '80px',
resHeight: '40px'
}, options);
var $window = $(window)
var scrolling = function(){
$window.scroll(function(){
if( $window.scrollTop() > settings.topSpacing ) {
$(this).css({position: 'fixed', top: '0px'});
$(this).stop().animate({height : settings.resHeight}, 200);
} else {
$(this).css({position: 'static'});
$(this).stop().animate({height : settings.initialHeight}, 200);
}
});
};
return this.each(scrolling);
};
})(jQuery);
$('nav').stickynav();
结果有点糊涂,我做错了什么。
请帮忙,如果不是,很难解释变化。