實現簡單的js拖動庫

在ajax應用程序中,拖動技術是經常要用到的,在桌面程序中,這是很常用也很容易實現的,但是在ajax中用javascript就不是這麼容易實現的了。現在我們製作一個js拖動庫來實現,先講下簡單思路。
今天先介紹實現拖動的基本方法,在以後的文章中,我們來完善這個庫。這個庫主要由3步建立。

當鼠標鍵按下時,記錄要移動的對象和對象的座標。
當鼠標移動時,改變對象的left,top屬性來實現對象的移動。
當鼠標鍵被釋放時,釋放對象。
爲了方便理解核心代碼,我先把html,css和包含全局變量的js代碼寫出來。
.se4Drag{ position:absolute; background-color:#00FFFF; }
<body> <div class="se4Drag"> 拖動版塊<br /> www.se4.cn </div> </body>
var se4_move_object=null var se4_object_X=0; var se4_object_Y=0; var se4_mouse_X=0; var se4_mouse_Y=0;
現在可以看核心代碼了,首先是當鼠標鍵按下時,記錄要移動的對象和對象的座標。
function se4OnMouseDown(){ se4_move_object=window.event.srcElement; if (se4_move_object.className=="se4Drag"){ //設置樣式,可自己定義 se4_move_object.style.cursor="move"; //記錄對象當前座標 se4_object_X=se4_move_object.style.pixelLeft; se4_object_Y=se4_move_object.style.pixelTop; }else{ se4_move_object=null; } }

第二步:當鼠標移動時,改變對象的left,top屬性來實現對象的移動。
function se4OnMouseMove(){ if (se4_move_object==null) return false; se4_mouse_X=window.event.x; se4_mouse_Y=window.event.y; se4_move_object.style.left=se4_mouse_X+"px"; se4_move_object.style.top=se4_mouse_Y+"px"; }
第三步:當鼠標鍵被釋放時,釋放對象。
function se4OnMouseUp(){ if (se4_move_object==null) return false; //把設置的樣式改回來 se4_move_object.style.cursor=""; //釋放對象 se4_move_object=null; }
第四步:把剛纔的函數綁定到document上。
document.onmousedown=se4OnMouseDown; document.onmousemove=se4OnMouseMove; document.onmouseup=se4OnMouseUp;
到這裏基本就可以實現拖動了,如果你看明白了,恭喜你,但是不要太高興,這只是開始,還有好多比如瀏覽器兼容等的問題沒有解決,我在以後的文章中會完善這個js拖動庫的。如果你沒有看明白可以聯繫我(se4.cn站長)。
原文:[url=http://www.se4.cn/article/200711/24001.asp]http://www.se4.cn/article/200711/24001.asp[/url] 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章