Javascript实现最简跨平台面向对象拖拽
?
一、開篇
拖拽已經是個Javascript的老話題了,但是也是最經典的問題之一。在這里,我用面向對象的方法實現了簡單的拖拽,這是做復雜js效果的基礎。
二、原理
拖拽的原理很簡單,就是捕獲鼠標事件,作出應有的相應。
需要處理的鼠標事件有三個:mousedown mousemove mouseup,下面分別介紹在各個事件需要處理一些什么事情。
1、?mousedown
(1)?????? 將鼠標所點擊的對象position設置為absolute,這樣才可以通過設置top和left的值讓元素動起來;
(2)?????? 獲得鼠標點擊的這個時刻鼠標與拖動對象邊界的坐標差(offsetX和offsetY),以便在拖動的時候來確定拖動對象的位置。
(3)?????? 注冊document的mousemove事件
2、?mousemove
(1)?????? 通過offsetX和offsetY以及鼠標的即時位置來確定被拖動對象的即時位置。
3、?mouseup
(1)?????? 刪除document注冊的mousemove事件
三、實現
主要的代碼如下:
?
function?Drag(oHandle,oContainer){????if(typeof?Drag.zIndex?==?"undefined")
????????Drag.zIndex?=?1000;
????var?handle?=?oHandle;
????var?container?=?oContainer;
????var?offsetX?=?0;
????var?offsetY?=?0;
????var?isDragging?=?false;
????
???? var?mouseDown?=?function(){
????????oEvent?=?oEventUtil.getEvent();
????????Drag.zIndex++;
????????container.style.zIndex?=?Drag.zIndex;
????????if(oEvent.button?==?1?||?oEvent.button?==?0){
????????????container.style.position?=?'absolute';
????????????offsetX?=??oEvent.pageX?-?container.offsetLeft;
????????????offsetY?=?oEvent.pageY?-?container.offsetTop;
????????????if(handle.innerHTML?==?""){
????????????????handle.innerHTML?=?"?";
????????????};
????????????oEventUtil.addEventHandler(document,"mousemove",mouseMove);
????????????isDragging?=?true;
????????}
????};
????
??? var?mouseMove?=?function(){
????????oEvent?=?oEventUtil.getEvent();
????????if(isDragging){
????????????container.style.top?=?(oEvent.pageY?-?offsetY)?+?'px';
????????????container.style.left?=?(oEvent.pageX?-?offsetX)?+?'px';
????????}
????};
????var?mouseUp?=?function(){
????????isDragging?=?false;
????????oEventUtil.removeEventHandler(document,"mousemove",mouseMove);
????};
????
????oEventUtil.addEventHandler(handle,"mousedown",mouseDown);
????oEventUtil.addEventHandler(handle,"mouseup",mouseUp);
}
?
考慮到很多拖拽都是移動拖動條整個外框也要一起移動,在實例化這個類的時候就傳遞兩個參數,一個是拖動條的對象,一個是外框對象。
如果要使用很簡單,代碼如下:
window.onload?=?function(){????var?drag1?=?new?Drag(document.getElementById("header"),document.getElementById("container"));
????var?drag?=?new?Drag(document.getElementById("Div2"),document.getElementById("Div1"));
}
?
四、注意幾點
1、這里使用了對事件進行過封裝的oEventUtil,這樣使得拖拽的結構看起來更清晰。oEventUtil的具體代碼可以參看我以前寫的一篇博客,也可以直接下載本頁的實例。
2、鼠標的三個事件所注冊的對象是不一樣的,mousedown和mouseup都要注冊到拖動條這個對象上,而mousemove必須注冊到document上,這樣拖拽才能正常工作。因為如果把mousemove注冊到拖動條上的話,鼠標移動過快就會移出拖動條,立刻就失去了mousemove的響應,而注冊到document上就不會出現這個問題,因為鼠標一直都在document上移動,一直都會相應。
五、實例下載
?點此下載示例?
轉載于:https://www.cnblogs.com/LongWay/archive/2008/09/03/1282492.html
總結
以上是生活随笔為你收集整理的Javascript实现最简跨平台面向对象拖拽的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 虚拟机安装jdk步骤及命令
- 下一篇: 一道面试题:猫大叫了一声...