zl程序教程

您现在的位置是:首页 >  后端

当前栏目

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

JS事件 无法 原因 捕获 滚动条 猜想
2023-06-13 09:14:33 时间
比如一个网页的聊天室,滚动条会随着内容的增加自动往下滚动。
当用户鼠标在滚动条上按下的时候,我们可以假设他(她)正在浏览聊天内容,那么这个时候好的用户体验就不能让滚动条再自动滚动了。
为了实现这个功能,可能大家首先会想到的就是mousedown和mouseup事件了。
可是具体实现的时候我们会发现在滚动条上按下鼠标左键再松开的时候,捕获不到mouseup了。如下面例子
复制代码代码如下:

<html>
<head>
<title></title>
<scripttype="text/javascript">
varcaptureTarget=null;
functiondown(obj,e){
captureTarget=obj;
//如果是IE可以打开注释
//captureTarget.setCapture();
e=e?e:window.event;
}
functionup(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>
<divstyle="width:200px;height:200px;overflow:scroll"onmousedown="down(this,event);">
<divstyle="height:500px;width:500px"></div>
</div>
</body>
</html>

保存为html格式文件,浏览器打开,然后在滚动条上左键点击试试,再在其他地方点击试试。
由于没有深入研究过W3C的文档,这里只能猜想。
考虑到滚动条的特性,可能浏览器在鼠标按下滚动条的时候给滚动条setCapture了,而鼠标松开之后给他releaseCapture,滚动条又不属于Dom对象,所以在鼠标释放之前无法捕获mouseup事件。