JS無法捕獲滾動條上的mouse up事件的猜想


原文地址:http://www.cnblogs.com/lln7777/archive/2012/03/21/2409404.html

比如一個網頁的聊天室,滾動條會隨着內容的增加自動往下滾動。

當用戶鼠標在滾動條上按下的時候,我們可以假設他(她)正在瀏覽聊天內容,那么這個時候好的用戶體驗就不能讓滾動條再自動滾動了。

為了實現這個功能,可能大家首先會想到的就是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事件。

純粹猜想,歡迎板磚。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM