首页 > 解决方案 > 重叠滚动事件和滚轮事件时出现难以理解的行为

问题描述

window.addEventListener("wheel",function(){
  console.log("wheel");
  window.addEventListener('scroll', function(e){
    console.log("scroll");
  });
})

第一次操作鼠标滚轮时,我认为只有“滚轮”显示,window.addEventListener("scroll",function(){...})唯一需要注册的。但是,看输出,“轮子”和“滚动”是同时输出的。

2.

window.addEventListener("scroll",function(){
  console.log("scroll");
  
  window.addEventListener('wheel', function(e){
    console.log("wheel");
  });
});

第一次操作鼠标滚轮时,如我所料,只输出“滚动”。但是,如果再次操作,则按“轮”“滚动”的顺序输出。为什么先轮输出?

标签: javascriptdom-events

解决方案


为了更好地理解这一点,我提供了,

<body style="height: 150vh;">

请在视图中按“向下箭头”并查看控制台。只会打印“滚动”。--> 它不会触发滚轮,

但是,如果您使用“鼠标滚轮”滚动,您将在控制台中看到“滚轮”和“滚动”作为输出。,

更多信息:

scroll 当用户通过任何方式(箭头键、滚动条或鼠标滚轮)滚动元素时触发。您无法阻止滚动。

Wheel 当用户使用鼠标滚轮时触发。您可以阻止此事件的默认设置。请注意,页面不必滚动才能触发此事件。

window.addEventListener("scroll",function(){
  console.log("scroll");}); 

  window.addEventListener("wheel",function(){
    console.log("wheel");});
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>
<body style="height: 150vh;">
  <h1>test</h1>
    <script src="test.js"></script>
</body>
</html>


推荐阅读