/p>
window.onload = function(){
var oBoxOne = new Drag();
oBoxOne.init('boxOne',200,200,function(){
document.title = 'Hello';
});
var oBoxTwo = new Drag();
oBoxTwo.init('boxTwo',200,200,function(){
document.title = 'World!';
});
}
function Drag(){
this.obj = null;
this.disX = 0;
this.disY = 0;
this.width = 0;
this.height = 0;
}
Drag.prototype.init = function(id,w,h,callback){
var That = this;
this.obj = document.getElementById(id);
// 设置块box宽度高度
this.obj.style.cssText = 'width:'+w+'px;height:'+h+'px;';
this.width = w;
this.height = h;
this.obj.onmousedown = function(ev){
var ev = ev || window.event;
That.fnMouseDown(ev);
document.onmousemove = function(ev){
var ev = ev || window.event;
That.fnMouseMove(ev);
}
document.onmouseup = function(ev){
var ev = ev || window.event;
That.fnMouseUp(ev);
callback();
}
}
}
//鼠标上的按钮被按下触发
Drag.prototype.fnMouseDown = function(ev){
this.disX = ev.clientX - this.obj.offsetLeft;
this.disY = ev.clientY - this.obj.offsetTop;
}
//鼠标按下后,松开时触发
Drag.prototype.fnMouseUp = function(){
document.onmousemove = null;
document.onmouseup = null;
}
//鼠标移动时触发
Drag.prototype.fnMouseMove = function(ev){
var winW = (document.documentElement.clientWidth || document.body.clientWidth) - this.width,
winH = (document.documentElement.clientHeight || document.body.clientHeight) - this.height,
tgL = ev.clientX - this.disX,
tgT = ev.clientY - this.disY;
// 处理拖拽边界
if(tgL >= 0){
tgL = tgL > winW ? winW : tgL;
}else{
tgL = 0;
}
if(tgT >= 0){
tgT = tgT > winH ? winH : tgT;
}else{
tgT = 0;
}
this.obj.style.left = tgL + 'px';
this.obj.style.top = tgT +'px';
}