js拖拽——將滑鼠事件響應範圍擴大到整個系統案頭

來源:互聯網
上載者:User

起因: 最近在做一個可拖拽的拓撲圖,遇到的這個問題:如果執行拖拽操作的時候滑鼠拖動很快,可能會出現滑鼠脫離頁面乃至瀏覽器的範圍,如果這時鬆開滑鼠按鍵,那麼將不能響應滑鼠的onmouseup事件,從而導致onmouseup和onmousemove事件不能被釋放掉。 對於這個問題,網上很多相似的文章寫瞭解決辦法,但都有些毛病,我在這裡總結歸納一下。 解決辦法: 方案一:針對ie和Firefox瀏覽器 ie瀏覽器和Firefox提供了setCapture 和 releaseCapture函數來解決該問題。簡單寫個小例子: 複製代碼 1 /*...html部分略...*/ 2  3 var i = 0; 4 div1.onmousedown = function() { 5       div1.setCapture(); //用dom元素調用該函數相當於將該dom元素上的事件交給作業系統去維護,從而讓該dom元素上的事件響應不依賴於瀏覽器 6       div1.onmousemove = function() { 7          console.log(i++); 8       } 9       div1.onmouseup = function() {10           div1.onmouseup = null;11         div1.onmousemove = null;12         div1.releaseCapture(); //拖拽結束後要釋放掉13       }14 }複製代碼  方案二:針對chrome瀏覽器 悲催的是chrome瀏覽器並沒有提供上述函數的實現,那隻能另闢蹊徑了。方法就是在window對象上註冊onmousedown、onmousemove、onmouseup事件。這樣只要在視窗內觸發onmousedown事件之後,無論您滑鼠移動到什麼地方,都能onmousemove和onmouseup事件。至於您要對哪個具體的dom元素進行操作,您可以在onmousedown事件的回呼函數中通過event.target擷取目標元素對象,然後再用call去執行相應函數即可。例子如下: 複製代碼 1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title></title> 6 </head> 7  8 <body> 9 <div id="div1" style="width:100px; height:100px; border:1px solid red">10     11 </div>12 13 </body>14 </html>15 <script>16     var i = 0;17     window.onmousedown= function(event) {18         var targetObj = event.target;19         if (targetObj.id == "div1") { //只有在id為div1的元素上按下滑鼠左鍵才能觸發滑鼠移動事件20             window.onmousemove = function() {21                 div1Move.call(targetObj);22             }23             window.onmouseup= function() {24                 window.onmouseup = null;25                 window.onmousemove = null;26             }27         }28     }29     30     //滑鼠移動時執行的事件31     function div1Move() {32         console.log(i++);33     }34 </script>複製代碼注意:1、該解決方案不適用於ie8及以下瀏覽器。因為這些瀏覽器不支援在window對象上註冊事件。 2、該解決方案也不適用於iframe,您可以把上面的例子放到iframe中去試一試。原因大概是因為系統只維護最頂層window上的事件。  

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.