html拖拽组件,纯js实现拖拽组件

/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';

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值