1

对我来说,需要一些关于如何正确编写 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();

结果有点糊涂,我做错了什么。

请帮忙,如果不是,很难解释变化。

4

1 回答 1

2

我看到的主要问题是$window.scroll您使用的函数内部this
但是this指的是那个上下文中的窗口..

您将需要存储对nav元素的引用并使用它而不是this.

所以整体var scrolling = ...应该变成

var scrolling = function(){
    var self = $(this);
    $window.scroll(function(){
        if( $window.scrollTop() > settings.topSpacing ) {
            self.css({position: 'fixed', top: '0px'});
            self.animate({height : settings.resHeight}, 200);
        } else {
            self.css({position: 'static'});
            self.animate({height : settings.initialHeight}, 200);
        }
    });
};

另一个改进是存储固定导航的当前状态,这样您就不会在每次滚动时执行动画,而仅在您想要更改状态时执行。

演示代码在http://jsfiddle.net/gaby/ALDjx/2/

var scrolling = function () {
        var self = $(this);
        self.data('stickyState', false);

        $window.scroll(function () {
            var state = self.data('stickyState'),
                shouldBeFixed = $window.scrollTop() > settings.topSpacing;

            if (!state && shouldBeFixed) {
                self.css({
                    position: 'fixed',
                    top: '0px'
                }).animate({
                    height: settings.resHeight
                }, 200);
                self.data('stickyState', true);
            } else if (state && !shouldBeFixed) {
                self.css({
                    position: 'static'
                }).animate({
                    height: settings.initialHeight
                }, 200);
                self.data('stickyState', false);
            }
        });
    };
于 2013-06-22T18:50:49.393 回答