0

我试图为浮动元素制作最小的 jquery 插件,当它们位于页面的末尾时(因此,没有默认值或选项),但是虽然以下内容适用于 1 个“粘性”元素,但我在使其工作时遇到问题多个元素。我意识到我需要返回 this.each 但无法找到最好的方法。当然我不想在每个循环中调整大小和滚动?

下面的代码:

(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 ));
4

1 回答 1

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 ));
于 2013-09-09T09:39:02.457 回答