1、通过mousedown事件,记录被拖拽物体和鼠标按下位置的相对坐标
2、在mousedown事件里面添加mousemove事件,获取当前鼠标的坐标并减去物体与鼠标的相对坐标(步骤一中记录的相对位置),并将新坐标赋给被拖拽物体
3、当松开鼠标,触发mouseup事件,在mouseup事件里给Mousemove事件赋空值null
function limitDrag(node){
var offsetX = 0;
var offsetY = 0;
node.onmousedown = function(ev){
var e = ev || window.event;
//1、记录相对位置
offsetX = e.clientX - node.offsetLeft;
offsetY = e.clientY - node.offsetTop;
//2、添加鼠标移动
document.onmousemove = function(ev){
var e = ev || window.event;
var l = e.clientX - offsetX;
if(l <= 0){
l = 0;
}
var windowWidth = document.documentElement.clientWidth || document.body.clientWidth;
if(l >= windowWidth - node.offsetWidth){
l = windowWidth - node.offsetWidth;
}
var t = e.clientY - offsetY;
if(t <= 0){
t = 0;
}
var windowHeight = document.documentElement.clientHeight || document.body.clientHeight;
if(t >= windowHeight - node.offsetHeight){
t = windowHeight - node.offsetHeight;
}
node.style.left = l + 'px';
node.style.top = t + 'px';
}
}
document.onmouseup = function(){
document.onmousemove = null;
}
}