jquery 函数销毁滚动事件

jquery function destroy on scroll event

到目前为止,我已经构建了一个 jquery 函数,该函数在滚动时将 html 元素粘贴到页面顶部,但滚动事件销毁不起作用。我知道我应该将滚动事件的函数存储在变量中,但我不知道以后如何销毁它。 有人能帮我吗? 到目前为止,这是我的代码:

(function ( $ ) {

$.fn.sticky = function(data) {
    var settings = $.extend({
        parent: null,
        offsetTop: 0,
        offsetBottom: 0,
        fixBottom: true,
        destroy: false
    }, data );

    this.each(function() {
        var elm = $(this),
        parent = $(settings.parent);

        if(settings.parent === null) {
            parent = elm.parent();
        }

        var elmTop = elm.offset().top,
            elmLeft = elm.offset().left,
            elmWidth = elm.width(),
            elmHeight = elm.height(),
            parentTop = parent.offset().top,
            parentHeight = parent.outerHeight(true),
            offs = elmTop - settings.offsetTop,
            margin_top = elmTop - parentTop,
            margin_bottom = parentHeight - elmHeight - margin_top,
            diff = parentHeight - elmHeight + parentTop - settings.offsetTop - settings.offsetBottom;

        var sticky_elm = function() {

            var w_top = $(window).scrollTop();

            if(w_top > offs && w_top < diff) {
                elm.attr("style", "position: fixed; top: "+settings.offsetTop+"px; left: "+elmLeft+"px; margin-left: 0;");
                if(!elm.next('[data-sticket-controller]').length) {
                    elm.after('<div data-sticket-controller style="visibility: hidden; opacity: 0; position: relative; width: '+elmWidth+'px; height: '+elmHeight+'px;"></div>');
                }
            }
            else if(w_top >= diff) {
                if(settings.fixBottom) {
                    elm.attr("style", "position: absolute; bottom: "+settings.offsetBottom+"px; left: "+elmLeft+"px; margin-left: 0;");
                }
            }
            else {
                elm.removeAttr("style");
                elm.next("[data-sticket-controller]").remove();
            }
        }

        if(settings.destroy) {
            $(document).off("scroll", sticky_elm);
        }
        else {
            $(document).on("scroll", sticky_elm);
        }
    });
};

}( jQuery ));

事件命名空间在这种情况下会很有用,因为事件侦听器在 $(document) 本身上,所以我更新了 fiddle 事件命名空间和每个粘性元素的唯一标识符只要我们有粘性元素 ID,我们就可以在以后随时关闭事件监听器。

https://jsfiddle.net/c289wLe1/11/