到目前为止,我已经构建了一个jquery函数,在滚动时将html元素粘贴到页面顶部,但在scroll事件上销毁则不起作用。我知道我应该将滚动事件的函数存储在变量中,但是我不知道以后如何销毁它。 有人能帮我吗? 到目前为止,这是我的代码:
(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 ));
答案 0 :(得分:0)
在这种情况下,事件名称空间会很有用,因为事件侦听器位于$(document)
本身,所以我用事件名称空间和每个粘性元素的唯一标识符更新了小提琴,以便我们可以关闭只要有粘性元素ID,事件监听器就可以在以后的任何时间。