Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
3.9k views
in Technique[技术] by (71.8m points)

js如何响应滚动条的点击事件?

<!DOCTYPE html> 
<html lang="en"> 
  <head> 
    <meta charset="UTF-8" /> 
    <meta name="viewport" content="width=device-width, initial-scale=1.0" /> 
    <meta http-equiv="X-UA-Compatible" content="ie=edge" /> 
    <title>Document</title> 
    <style> 
      .wrap {
        height: 500px;
        width: 300px;
        overflow: auto;
      }
      .content {
        height: 5000px;
        width: 1000px;
      }
    </style> 
  </head> 
  <body> 
    <div class="wrap"><div class="content">1</div></div> 
    <script> 
      document.addEventListener("click", () => {
        alert("click");
      });
      // 能否绑定document上任意的scroll
      document 
        .getElementsByClassName("wrap")[0]
        .addEventListener("scroll", () => {
          console.log("scroll");
        });
    </script> 
  </body> 
</html> 

有这么一段html,我想在用户点击滚动条时进行监测,该如果实现?
直接在document上绑定click事件可以相应所有的元素(除了滚动条)。

转换为监听滚动:
但是如果直接在document绑定scroll,那么滚动.wrap元素时就无法响应。
如果界面上有很多元素,我只想监听滚动条滚动时的事件,需要每个都进行绑定吗?


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
  <style>
    #box {
      margin: 500px 0;
      height: 500px;
      overflow: scroll;
    }
    #box2 {
      height: 1000px;
      background: red;
    }
  </style>
</head>
<body>
  <div id="box">
    <div id="box2"></div>
  </div>
  <script>
    document.addEventListener('scroll', console.log, true)
  </script>
</body>
</html>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...