|
源代码网推荐
本文示例源代码或素材下载
一、开篇
拖拽已经是个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事件
三、实现
主要的代码如下:
functionDrag(oHandle,oContainer){ if(typeofDrag.zIndex=="undefined") Drag.zIndex=1000; varhandle=oHandle; varcontainer=oContainer; varoffsetX=0; varoffsetY=0; varisDragging=false; varmouseDown=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; } }; varmouseMove=function(){ oEvent=oEventUtil.getEvent(); if(isDragging){ container.style.top=(oEvent.pageY-offsetY)+"px"; container.style.left=(oEvent.pageX-offsetX)+"px"; } }; varmouseUp=function(){ isDragging=false; oEventUtil.removeEventHandler(document,"mousemove",mouseMove); }; oEventUtil.addEventHandler(handle,"mousedown",mouseDown); oEventUtil.addEventHandler(handle,"mouseup",mouseUp); }
考虑到很多拖拽都是移动拖动条整个外框也要一起移动,在实例化这个类的时候就传递两个参数,一个是拖动条的对象,一个是外框对象。
如果要使用很简单,代码如下:
window.onload=function(){ vardrag1=newDrag(document.getElementById("header"),document.getElementById("container")); vardrag=newDrag(document.getElementById("Div2"),document.getElementById("Div1")); }
四、注意几点
1、这里使用了对事件进行过封装的oEventUtil,这样使得拖拽的结构看起来更清晰。oEventUtil的具体代码可以参看我以前写的一篇博客,也可以直接下载本页的实例。
2、鼠标的三个事件所注册的对象是不一样的,mousedown和mouseup都要注册到拖动条这个对象上,而mousemove必须注册到document上,这样拖拽才能正常工作。因为如果把mousemove注册到拖动条上的话,鼠标移动过快就会移出拖动条,立刻就失去了mousemove的响应,而注册到document上就不会出现这个问题,因为鼠标一直都在document上移动,一直都会相应
本文作者:未知
源代码网供稿. |