jquery鼠标滚停止传播

时间:2013-06-08 06:21:13

标签: jquery javascript-events mousewheel

如何使用mousewheel事件侦听器停止传播?

content元素上使用鼠标滚轮时,整个文档也会滚动

这不起作用

content.on('mousewheel', function(e, delta){
    content.scrollTop(content.scrollTop() - (40 * delta));
    set_bar();
    e.stopPropagation();
});

溶液

content.on('mousewheel', function(e, delta){
    content.scrollTop(content.scrollTop() - (40 * delta));
    set_bar();
    return false;
});

2 个答案:

答案 0 :(得分:6)

我认为你混淆了stopPropgation并阻止了默认。

  • stopPropagation阻止事件冒泡事件链。

  • preventDefault可防止发生默认操作 元件。在这种情况下,它会阻止滚动,对于单击事件 例如,它将停止链接将您带到URL 在href属性中定义。

  • 另一方面,
  • return false会做这两件事。

它是一个重要的区别,因为您可能希望使用事件冒泡进行事件委派,同时防止默认操作。

有关更多信息,请参阅这两篇文章:

Difference between preventDefault and return false

Difference between preventDefault and stopPropagation

答案 1 :(得分:2)

原始解决方案 非常接近 这是有效的:

    $(".myScrollableDiv").on("mousewheel",function(e) {
        var scrollRate = 100;
        var $t = $(this);
        var dy = e.originalEvent.deltaY * scrollRate;
        $t.scrollTop($t.scrollTop() + dy);
        e.preventDefault();
    });

我认为主要原因是jQuery没有给我们第二个参数(delta),但它可以在事件本身中找到。没关系,没关系。