JS无法捕获滚动条上的mouse up事件的原因猜想

  比如一个网页的聊天室,滚动条会随着内容的增加自动往下滚动。

  当用户鼠标在滚动条上按下的时候,我们可以假设他(她)正在浏览聊天内容,那么这个时候好的用户体验就不能让滚动条再自动滚动了。

  为了实现这个功能,可能大家首先会想到的就是mouse down 和 mouse up事件了。

  可是具体实现的时候我们会发现在滚动条上按下鼠标左键再松开的时候,捕获不到mouse up了。如下面例子

  

复制代码 代码如下:

  <html>

  <head>

  <title></title>

  <script type="text/javascript">

  var captureTarget = null;

  function down(obj, e) {

  captureTarget = obj;

  // 如果是IE可以打开注释

  // captureTarget.setCapture();

  e = e ? e : window.event;

  }

  function up(obj,e) {

  // if (captureTarget)

  // captureTarget.releaseCapture();

  e = e ? e : window.event;

  div2.innerText = e.srcElement.tagName;

  }

  document.addListener = function(event, callback) {

  if (!document.all)

  this.addEventListener(event, callback);

  else

  this.attachEvent("on"+event, callback);

  }

  document.addListener("mouseup", function(){alert(1);});

  </script>

  </head>

  <body >

  <div style="width:200px;height:200px;overflow:scroll" onmousedown="down(this, event);">

  <div style="height:500px; width:500px"></div>

  </div>

  </body>

  </html>

  保存为html格式文件,浏览器打开,然后在滚动条上左键点击试试,再在其他地方点击试试。

  由于没有深入研究过W3C的文档,这里只能猜想。

  考虑到滚动条的特性,可能浏览器在鼠标按下滚动条的时候给滚动条setCapture了,而鼠标松开之后给他releaseCapture,滚动条又不属于Dom对象,所以在鼠标释放之前无法捕获mouseup事件。