JavaScript的div拖拽,用构造函数,在鼠标移动太快时会使onmousemove失效...
发布网友
我来回答
共1个回答
热心网友
你的代码没用代码排版太杂乱,我直接把自己写的拖拽给你参考一下,这段代码只是无聊时写的,所以没写吸附和区域*,你可以参考修改一下。使用方法在底部。
function ClickMove(id){
var _this = this;
this.ele = document.querySelector(id);
this.left = this.ele.offsetLeft;
this.top = this.ele.offsetTop;
this.ele.onmousedown = function(ev){
_this.mDown(ev);
}
}
ClickMove.prototype.mDown = function(ev){
var _this = this;
if( getComputedStyle(this.ele).position != 'absolute' ) this.ele.style.position = 'relative';
var eleX = ev.clientX - this.ele.offsetLeft;
var eleY = ev.clientY - this.ele.offsetTop;
document.documentElement.onmousemove = function(ev){
_this.ele.style.left = ev.clientX - eleX - _this.left + 'px';
_this.ele.style.top = ev.clientY - eleY - _this.top + 'px';
}
document.documentElement.onmouseup = function(){
this.onmousemove = null;
}
}
/*
元素你只要给一个宽高背景就好,其他的不用给都可以。
使用方法:写ID或者class名字
class方式demo: var div1 = new ClickMove('.box1');
id方式demo: var div1 = new ClickMove('#box1');
*/