实现拖拽其实很简单
1.首先绑定事件,一般应该是鼠标移入事件 onmouseover
2.然后获取鼠标移入后距离父元素的左,上边距,e.offsetLeft和e.offsetTop
3.然后绑定鼠标移动事件 onmousemove,计算出 鼠标距离浏览器左边,上边的距离 e.pageX和e.pageY
然后计算出可移动的范围就可以,记得做边界处理、
代码如下:
var box = document.getElementById("box");
box.onmousedown = function(e){
var e = e || event;
var x = e.offsetX;
var y = e.offsetY;
document.onmousemove = function(e){
var e = e || event;
var l = e.pageX - x;
var t = e.pageY - y;
//做一个边界处理
/*if(l < 0){
l = 0;
}else if(l > document.documentElement.clientWidth - 200){
l = document.documentElement.clientWidth - 200;
}
if(t < 0){
t = 0;
}else if(t > document.documentElement.clientHeight - 200){
t = document.documentElement.clientHeight - 200;
}*/
var lNum = document.documentElement.clientWidth - 200;
var tNum = document.documentElement.clientHeight - 200;
l = l < 0 ? 0 : (l > lNum ? lNum : l);
t = t < 0 ? 0 : (t > tNum ? tNum : t);
box.style.left = l + "px";
box.style.top = t + "px";
}
document.onmouseup = function(){
document.onmousemove = null;
}
return false;
}