捕获鼠标滚轮,同时防止JavaScript中的页面滚动

时间:2017-05-18 16:52:23

标签: javascript

当鼠标位于div上或div中的元素上时,我需要捕获鼠标滚轮事件,并阻止页面滚动。

此论坛中有一些解决方案(例如thisthis),但页面会一直滚动。

解决方案必须是纯JavaScript(即没有jQuery等)。

1 个答案:

答案 0 :(得分:2)

您只需要在捕获事件后取消该事件。

// This disables the event for the entire document.
// Substitute a reference to the DOM element you wish to 
// deal with instead of "document" below.
document.addEventListener("mousewheel", function(evt){

  console.log("mousewheel event detected");

  evt.preventDefault(); // Cancel the event
  evt.stopPropagation() // Don't bubble

});