09年还在之前那家公司的时候就用js写了一个拖拽功能,但是写得很乱,最近xz又说到了这东西,之前因为搞得不是很透彻,所以决定重新写一下,代码很容易看,帖出来备忘一下。
var $ = function(id){
this.obj = document.getElementById(id);
this.obj.Draggable = function(){
this.onmousedown = this.InitMousePos;
};
Move = function(evt){
var evt = evt ||window.event;
var leftPox,topPox;
if(evt.pageX||evt.pageY)
{
leftPox = evt.pageX - mouseX;
topPox = evt.pageY - mouseY;
}
else//ie
{
leftPox = evt.clientX + document.documentElement.scrollLeft - mouseX;
topPox = evt.clientY+ document.documentElement.scrollTop-mouseY;
}
document.getElementById(id).style.left= leftPox;
document.getElementById(id).style.top = topPox;
}
this.obj.Release = function(){
if(this.releaseCapture){
this.releaseCapture();
document.onmousemove = null;
this.onmouseup = null;
}
else if(window.captureEvents){
document.onmousemove = null;
this.onmousemove = null;
this.onmouseup = null;
}
};
var mouseX,mouseY;
this.obj.InitMousePos = function(evt){
this.style.cursor="move";
this.style.position = "absolute";
var evt = evt || window.event;
if(evt.pageX||evt.pageY)
{
mouseX = evt.pageX-this.style.left.replace('px','');
mouseY = evt.pageY-this.style.top.replace('px','');
}
else//ie
{
mouseX =evt.clientX + document.documentElement.scrollLeft - this.style.left.replace('px','');
mouseY =evt.clientY+ document.documentElement.scrollTop-this.style.top.replace('px','');
}
document.onmousemove = Move;
this.onmouseup = this.Release;
};
return this.obj;
}
this.obj = document.getElementById(id);
this.obj.Draggable = function(){
this.onmousedown = this.InitMousePos;
};
Move = function(evt){
var evt = evt ||window.event;
var leftPox,topPox;
if(evt.pageX||evt.pageY)
{
leftPox = evt.pageX - mouseX;
topPox = evt.pageY - mouseY;
}
else//ie
{
leftPox = evt.clientX + document.documentElement.scrollLeft - mouseX;
topPox = evt.clientY+ document.documentElement.scrollTop-mouseY;
}
document.getElementById(id).style.left= leftPox;
document.getElementById(id).style.top = topPox;
}
this.obj.Release = function(){
if(this.releaseCapture){
this.releaseCapture();
document.onmousemove = null;
this.onmouseup = null;
}
else if(window.captureEvents){
document.onmousemove = null;
this.onmousemove = null;
this.onmouseup = null;
}
};
var mouseX,mouseY;
this.obj.InitMousePos = function(evt){
this.style.cursor="move";
this.style.position = "absolute";
var evt = evt || window.event;
if(evt.pageX||evt.pageY)
{
mouseX = evt.pageX-this.style.left.replace('px','');
mouseY = evt.pageY-this.style.top.replace('px','');
}
else//ie
{
mouseX =evt.clientX + document.documentElement.scrollLeft - this.style.left.replace('px','');
mouseY =evt.clientY+ document.documentElement.scrollTop-this.style.top.replace('px','');
}
document.onmousemove = Move;
this.onmouseup = this.Release;
};
return this.obj;
}
调用非常简单,只要在页面加载后调用如下代码就可以实现拖拽
window.onload=function()
{
$(”Contain”).Draggable();
}
这里遇到一个问题,就是如果为元素添加onmousemove事件,则拖拽速度太快的话会出现元素跟不上鼠标动作的问题,解决办法是使用document.onmousermove来代替。参考文章:http://yangsp1.javaeye.com/blog/490521