代码:
function drag(t,p){
var point = p || null,
target = t || null,
resultx = 0,
resulty = 0;
(!point)? point = target : ''; //如果没有拖动点,则拖动点默认为整个别拖动元素
function getpos(t){
var offsetleft = 0,
offsettop = 0,
offsetparent = t;
while(offsetparent){
offsetleft+=offsetparent.offsetleft;
offsettop+=offsetparent.offsettop;
offsetparent = offsetparent.offsetparent;
}
return {'top':offsettop,'left':offsetleft};
}
function core(){
var width = document.body.clientwidth || document.documentelement.clientwidth,
height = document.body.clientheight || document.documentelement.clientheight;
maxwidth = width - target.offsetwidth,
maxheight = height - target.offsetheight;
(resultx >= maxwidth)? target.style.left = maxwidth+'px' : (resultx > 0)?target.style.left = resultx +'px': ''; //重置默认位置。
(resulty >= maxheight)? target.style.top = maxheight +'px' : (resulty > 0)?target.style.top = resulty +'px':''; //重置默认位置。
point.onmousedown=function(e){
var e = e || window.event,
coordx = e.clientx,
coordy = e.clienty,
posx = getpos(target).left,
posy = getpos(target).top;
point.setcapture && point.setcapture(); //将mouse事件锁定到指定元素上。
document.onmousemove=function(e){
var ev = e || window.event,
movex = ev.clientx,
movey = ev.clienty;
resultx = movex - (coordx - posx); //结果值是坐标点减去被拖动元素距离浏览器左侧的边距
resulty = movey - (coordy - posy);
(resultx > 0 )?((resultx < maxwidth)?target.style.left = resultx+'px' : target.style.left = maxwidth+'px') : target.style.left = '0px';
(resulty > 0 )?((resulty < maxheight)?target.style.top = resulty+'px' : target.style.top = maxheight+'px') : target.style.top = '0px';
ev.stoppropagation && ev.stoppropagation();
ev.preventdefault;
ev.returnvalue = false;
ev.cancelbubble = true;
};
};
document.onmouseup=function(){ // 解决拖动时,当鼠标指向的dom对象非拖动点元素时,无法触发拖动点的onmousedown的bug。
document.onmousemove = null;
point.releasecapture && point.releasecapture(); // 将mouse事件从指定元素上移除。
};
point.onmouseup=function(e){
var e = e || window.event;
document.onmousemove = null;
point.releasecapture && point.releasecapture();
};
}
core();
window.onresize = core;
}
使用方式:
drag(t,p)
/*
* 说明
* t 表示被拖动的元素
* p 表示拖动点
*/
// 注意:如果省略拖动点,默认可拖动的区域是整个被拖动元素