时间:2021-07-01 10:21:17 帮助过:42人阅读
Drag = {
obj: null,
init: function (options) {
options.handler.onmousedown = this.start;
options.handler.root = options.root || options.handler;
var root = options.handler.root;
root.onDragStart = options.dragStart || new Function();
root.onDrag = options.onDrag || new Function();
root.onDragEnd = options.onDragEnd || new Function();
},
start: function (e) {//此时的this是handler
var obj = Drag.obj = this;
obj.style.cursor = 'move';
e = e || Drag.fixEvent(window.event);
ex = e.pageX;
ey = e.pageY;
obj.lastMouseX = ex;
obj.lastMouseY = ey;
var x = obj.root.offsetLeft;
var y = obj.root..offsetTop;
obj.root.style.left = x + "px";
obj.root.style.top = y + "px";
document.onmouseup = Drag.end;
document.onmousemove = Drag.drag;
obj.root.onDragStart(x, y);
},
drag: function (e) {
e = e || Drag.fixEvent(window.event);
ex = e.pageX;
ey = e.pageY;
var root = Drag.obj.root;
var x = root.style.left ? parseInt(root.style.left) : 0;
var y = root.style.top ? parseInt(root.style.top) : 0;
var nx = ex - Drag.obj.lastMouseX + x;
var ny = ey - Drag.obj.lastMouseY + y;
root.style.left = nx + "px";
root.style.top = ny + "px";
Drag.obj.root.onDrag(nx, ny);
Drag.obj.lastMouseX = ex;
Drag.obj.lastMouseY = ey;
},
end: function (e) {
var x = Drag.obj.root.style.left ? parseInt(Drag.obj.root.style.left) : 0;
var y = Drag.obj.root.style.top ? parseInt(Drag.obj.root.style.top) : 0;
Drag.obj.root.onDragEnd(x, y);
document.onmousemove = null;
document.onmouseup = null;
Drag.obj = null;
},
fixEvent: function (e) {
e.pageX = e.clientX + document.documentElement.scrollLeft;
e.pageY = e.clientY + document.documentElement.scrollTop;
return e;
}
}
上面init主要处理一些初如化工作,如记录onDragStart、onDrag、onDragEnd三个事件, handler为处理拖动事件的那个元素,root为被拖动的元素。
当在handler上点击后触发Drag.start方法,Drag.start主要为记录住鼠标相对整个页面的位置;给document注册onmouseup、onmousemove事件,及触发onDragStart事件。
Drag.drag方法也很简单,主要作用就是更新被搬移元素位置,同时记录住鼠标相对整个页面的位置。
Drag.end方法就更简单了,就是做一些收尾工作。
最后给大家附段使用的代码吧,祝大家学习愉快!
代码如下:
Drag.init({
handler: document.getElementById("handler"),
root:document.getElementById("root");
});
<div id="root">
<h2 id="handler"></h2>
</div>