2016-01-14 53 views
1

嘿家伙我有这个jQuery代码的问题。其实它工作正常,但我不能关闭div后滚动我的滚轮。JQuery启用和禁用滚动

$(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; 
     }); 
    }); 
}); 

回答

2

我相信你的问题是这样的:

$('body').off('scroll mousewheel touchmove', function(e) { 
    e.preventDefault(); 
    e.stopPropagation(); 
    return false; 
}); 

这应该是:

$('body').off('scroll mousewheel touchmove'); 

当你传递一个函数来off它试图找到特定功能作为一个处理程序关于那个元素的事件。但是既然你在这两种情况下传递了一个匿名函数,当使用onoff时,它们是该函数的两个新实例,即使它们都执行相同的操作。所以它永远不会找到要移除的处理程序。在幕后的某个地方,想象这两种功能在内存中都有独特的地方,它们并不指向同一个地方,因为它们是匿名的并且定义在两个区域中。通过不传递一个函数到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; 
} 

,因为我们正在经历同样的功能,参照上述两个onoff它的工作。

+1

感谢您的快速响应,它的作品非常好! :D – VeloFX

+0

你很欢迎!乐于帮助。祝你好运! – AtheistP3ace

0

发生这种情况是因为e.preventDefault()将防止发生默认事件,在您的情况下,滚动。

http://jsfiddle.net/DHz77/1/

再见。