jQuery插件 - 返回this.each()的最佳方式

时间:2013-09-09 08:46:13

标签: jquery jquery-plugins

我试图为浮动元素制作最小的jquery插件,当它们位于页面的位置时(因此,没有默认值或选项)但是虽然以下适用于1'粘性'元素,但我有问题制作它适用于多个元素。我意识到我需要回归这个,但不能找到最好的方法。当然我不想在每个循环中调整大小和滚动?

以下代码:

(function ( $, undefined ) {
    $.fn.sticky = function() {
        var self = this,
            isStickyWidth = self.data('sticky'),
            isStickyActive = false,
            windowHeight,
            elOffset = self.offset().top,
            elHeight;
        $(document).on("scroll", function(){

            if(isStickyActive && windowHeight > elHeight) {
                var scrollPos = $('body').scrollTop();
                if(scrollPos > elOffset) {
                    self.css({'position':'fixed','top':'0px'});
                } else {
                    self.css({'position':'relative'});
                }
            }
        });
        $(window).on("resize", function(){
            windowHeight = $(window).height();
            elHeight = self.height();
            self.width(self.parent().width());
            if(isStickyWidth < $(window).width() ) {
                isStickyActive = true;
            } else {
                isStickyActive = false;
            }
        }).resize();
        return this; //need to return each in this example if binding to multiple DOM elements
    };
}( jQuery ));

1 个答案:

答案 0 :(得分:0)

试试这个,修改你的代码来迭代每个选择器,并允许链接。

(function ( $, undefined ) {
    $.fn.sticky = function() {
    return this.each(function(){        
        var self = this,
            isStickyWidth = self.data('sticky'),
            isStickyActive = false,
            windowHeight,
            elOffset = self.offset().top,
            elHeight;
        $(document).on("scroll", function(){

            if(isStickyActive && windowHeight > elHeight) {
                var scrollPos = $('body').scrollTop();
                if(scrollPos > elOffset) {
                    self.css({'position':'fixed','top':'0px'});
                } else {
                    self.css({'position':'relative'});
                }
            }
        });
        $(window).on("resize", function(){
            windowHeight = $(window).height();
            elHeight = self.height();
            self.width(self.parent().width());
            if(isStickyWidth < $(window).width() ) {
                isStickyActive = true;
            } else {
                isStickyActive = false;
            }
        }).resize();
    }):

    };

}( jQuery ));