2025-05-24

比如一個網頁的聊天室,滾動條會隨著內容的增加自動往下滾動。
當用戶鼠標在滾動條上按下的時候,我們可以假設他(她)正在瀏覽聊天內容,那麼這個時候好的用戶體驗就不能讓滾動條再自動滾動瞭。
為瞭實現這個功能,可能大傢首先會想到的就是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;
                p2.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 >
        <p style="width:200px;height:200px;overflow:scroll" onmousedown="down(this, event);">
            <p style="height:500px; width:500px"></p>
        </p>
    </body>

 

保存為html格式文件,瀏覽器打開,然後在滾動條上左鍵點擊試試,再在其他地方點擊試試。
 
由於沒有深入研究過W3C的文檔,這裡隻能猜想。
考慮到滾動條的特性,可能瀏覽器在鼠標按下滾動條的時候給滾動條setCapture瞭,而鼠標松開之後給他releaseCapture,滾動條又不屬於Dom對象,所以在鼠標釋放之前無法捕獲mouseup事件。

 

摘自  花落花相醉
 

發佈留言

發佈留言必須填寫的電子郵件地址不會公開。 必填欄位標示為 *