標籤:style blog http io ar color os 使用 sp
以前寫過一個拖動效果的Demo,拖拽元素新位置的計算是放在拖拽元素的mousemove事件中進行的。計算效率差,而且效果不好。所以一直有想怎樣才能做出jquery-ui那種順滑的拖拽效果。
其實順滑的拖拽效果的突破口有兩點:
- 事件捕捉要去捕捉document的滑鼠位置。
- 使用setInterval功能計算拖拽元素的新位置。
使用jQuery,經過一些簡單的重構和調試,將代碼完善如下:
drag.html
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <link type="text/css" rel="stylesheet" href="drag.css"> <script type="text/javascript" src="http://lib.sinaapp.com/js/jquery/1.9.1/jquery-1.9.1.min.js"></script> <script type="text/javascript" src="drag.js"></script> </head> <body> <div class="drag-panel"> <div class="title">Drag Panel</div> </div> </body> </html>
drag-panel.css ,做一些簡單的修飾:
.drag-panel{ position: absolute; width:300px; height:100px; border:1px solid black; cursor:default }.drag-panel .title{ text-align:center; background-color:yellowgreen; }
drag.js ,效果非常好:
$(function(){ var m_x0,m_y0, // 滑鼠座標0 m_x1,m_y1, // 滑鼠座標1 timeHandler //定時器控制代碼 var $dragPanel = $(".drag-panel"); var $dragTitle = $(".drag-panel .title"); // 滑鼠點擊,觸發拖拽過程。 $dragTitle.mousedown(function(e){ // 確定上一次調用的定時器是被清空了。 if(timeHandler!=0){ window.clearInterval(timeHandler); } // 確定滑鼠的初始位置。初始狀態下,滑鼠位置1與滑鼠位置0必須相同。 m_x0 = m_x1 = e.clientX; m_y0 = m_y1 = e.clientY; // 滑鼠移到需要撲捉document的滑鼠位置。 // mouseup表示滑鼠拖拽動作結束。該動作清空拖拽動期間的計算,且mouseup也只執行一次。 $(document).mousemove(mousemoveFunc).one("mouseup",mouseupFunc); // 定時計算拖拽元素位置。 timeHandler = window.setInterval(dragPos,30); }); // 滑鼠移動,擷取滑鼠的全域座標。 function mousemoveFunc(e){ window.console.log(new Date().getTime()); m_x1 = e.clientX; m_y1 = e.clientY; } // 滑鼠拖拽動作結束,清空的拖拽期間的計算。 function mouseupFunc(e){ if(timeHandler>0){ window.clearInterval(timeHandler); timeHandler = 0; $(document).unbind("mousemove",mousemoveFunc); } } // 拖拽計算。 function dragPos(){ var dm_x = m_x1 - m_x0; var dm_y = m_y1 - m_y0; var p0 = $dragPanel.offset(); $dragPanel.css("top",p0.top+dm_y+"px"); $dragPanel.css("left",p0.left+dm_x+"px"); m_x0 = m_x1; m_y0 = m_y1; } })
效果如下:
Drag Panel
Web的滑鼠拖動效果