Skip to content

Instantly share code, notes, and snippets.

@tangyangzhe
Created December 11, 2012 07:49
Show Gist options
  • Save tangyangzhe/4256645 to your computer and use it in GitHub Desktop.
Save tangyangzhe/4256645 to your computer and use it in GitHub Desktop.
js拖动
window.onload = function () {
drag(document.getElementById('drag'), [200, 400, 30, 300]);
};
function drag(o, r) {
o.firstChild.onmousedown = function () {
return false;
};
o.onmousedown = function (a) {
o.style.cursor = 'move';
var d = document;
if (!a) a = window.event;
var x = a.layerX ? a.layerX : a.offsetX,
y = a.layerY ? a.layerY : a.offsetY;
if (o.setCapture) o.setCapture();
else if (window.captureEvents) window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
d.onmousemove = function (a) {
if (!a) a = window.event;
if (!a.pageX) a.pageX = a.clientX;
if (!a.pageY) a.pageY = a.clientY;
var tx = a.pageX - x,
ty = a.pageY - y;
o.style.left = tx < r[0] ? r[0] : tx > r[1] ? r[1] : tx;
o.style.top = ty < r[2] ? r[2] : ty > r[3] ? r[3] : ty;
};
d.onmouseup = function () {
if (o.releaseCapture) o.releaseCapture();
else if (window.captureEvents) window.captureEvents(Event.MOUSEMOVE | Event.MOUSEUP);
d.onmousemove = null;
d.onmouseup = null;
o.style.cursor = '';
};
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment