这是一种非常简单的方法来停止传播,无需插件,只需 jQuery。
更新:代码已更新,可在 IE9+ 中正常工作。之前的版本没有测试过。
首先,在您的<div> 上创建一个类以将其标记为具有此行为。在我的示例中,我使用了 .Scrollable 类。
<div class="Scrollable">
<!-- A bunch of HTML here which will create scrolling -->
</div>
要禁用的 jQuery 是:
$('.Scrollable').on('DOMMouseScroll mousewheel', function(ev) {
var $this = $(this),
scrollTop = this.scrollTop,
scrollHeight = this.scrollHeight,
height = $this.height(),
delta = (ev.type == 'DOMMouseScroll' ?
ev.originalEvent.detail * -40 :
ev.originalEvent.wheelDelta),
up = delta > 0;
var prevent = function() {
ev.stopPropagation();
ev.preventDefault();
ev.returnValue = false;
return false;
}
if (!up && -delta > scrollHeight - height - scrollTop) {
// Scrolling down, but this will take us past the bottom.
$this.scrollTop(scrollHeight);
return prevent();
} else if (up && delta > scrollTop) {
// Scrolling up, but this will take us past the top.
$this.scrollTop(0);
return prevent();
}
});
本质上,它的作用是检测请求滚动的方向(基于originalEvent.wheelDelta:正=up,负=down)。如果mousewheel 事件的请求delta 将滚动超过<div> 的top 或bottom,请取消该事件。
尤其是在 IE 中,滚动事件越过子元素的可滚动区域,然后滚动到父元素,并且无论事件被取消,滚动都会继续。因为我们在任何情况下都取消了事件,然后通过jQuery来控制child上的滚动,所以这是被阻止的。
这大致基于this question解决问题的方式,但不需要插件,跨浏览器兼容IE9+。
Here is a working jsFiddle 演示实际代码。
Here is a working jsFiddle 演示代码在运行中,并更新为与 IE 一起使用。
Here is a working jsFiddle 演示代码在运行中,并更新为与 IE 和 FireFox 一起使用。有关更改必要性的更多详细信息,请参阅this post。