嘿,大家好,我的 jQuery 代码有问题。实际上它工作正常,但关闭 div 后我无法使用滚轮滚动。
$(document).ready(function() {
$("#add_item_inventory_toggle").click(function() {
$("#add_item_inventory").fadeOut("fast");
$("#add_item_inventory_toggle").hide();
$('body').off('scroll mousewheel touchmove', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});
});
$("#inventory_content_add_items").click(function() {
$("#add_item_inventory").fadeIn("fast");
$("#add_item_inventory_toggle").show();
$('body').on('scroll mousewheel touchmove', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});
});
});
最佳答案
我相信您的问题是这样的:
$('body').off('scroll mousewheel touchmove', function(e) {
e.preventDefault();
e.stopPropagation();
return false;
});
应该是:
$('body').off('scroll mousewheel touchmove');
当您将函数传递给 off
时,它会尝试查找该特定函数作为该元素上这些事件的处理程序。但是,由于在这两种情况下都传递了匿名函数,因此当使用 on
和 off
时,它们是该函数的两个新实例,即使它们都执行相同的操作。所以它永远找不到要删除的处理程序。在幕后的某个地方想象这两个函数在内存中都有一个独特的位置,它们没有指向同一个位置,因为它们是匿名的并且在两个区域中定义。通过不将函数传递给 off
,它只会删除附加到该元素的这些事件的任何函数。
现在,如果你这样做:
$(document).ready(function() {
$("#add_item_inventory_toggle").click(function() {
$("#add_item_inventory").fadeOut("fast");
$("#add_item_inventory_toggle").hide();
$('body').off('scroll mousewheel touchmove', stopScrolling);
});
$("#inventory_content_add_items").click(function() {
$("#add_item_inventory").fadeIn("fast");
$("#add_item_inventory_toggle").show();
$('body').on('scroll mousewheel touchmove', stopScrolling);
});
});
function stopScrolling (e) {
e.preventDefault();
e.stopPropagation();
return false;
}
它会起作用,因为我们将相同的函数引用传递给 on
和 off
。
关于JQuery 启用和禁用滚动,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34792733/