Skip to content

Instantly share code, notes, and snippets.

@hacke2

hacke2/drag.js

Created Aug 25, 2014
Embed
What would you like to do?
拖拽
var drag = document.getElementById('drag');
var inputX = document.getElementById('x');
var inputY = document.getElementById('y');
if(document.attachEvent){
drag.attachEvent('onmousedown',dragHandle);
}else{
drag.addEventListener('mousedown', dragHandle,false);
}
function dragHandle(event){
var event = event||window.event;
var startX = drag.offsetLeft;
var startY = drag.offsetTop;
var mouseX = event.clientX;
var mouseY = event.clientY;
var deltaX = mouseX - startX;
var deltaY = mouseY - startY;
if(document.attachEvent){
drag.attachEvent('onmousemove',moveHandle);
drag.attachEvent('onmouseup',upHandle);
/*IE中setCapture()的应用。它的作用是捕捉所有的MouseEvent,设置完成后,即使鼠标移出窗口注册的鼠标事件仍然能够被触发。它在此处的作用是当鼠标移动过快越出元素的边界使得原本将要失效的mousemove事件依然能够发挥作用。
*/
drag.setCapture();
}else{
document.addEventListener('mousemove',moveHandle,true);
document.addEventListener('mouseup',upHandle,true);
}
function moveHandle(event){
var event = event||window.event;
drag.style.left = (event.clientX - deltaX)+"px";
drag.style.top = (event.clientY - deltaY)+"px";
inputX.value=drag.style.left;
inputY.value=drag.style.top;
}
function upHandle(){
if(document.attachEvent){
drag.detachEvent('onmousemove',moveHandle);
drag.detachEvent('onmouseup',upHandle);
drag.releaseCapture();
}else{
document.removeEventListener('mousemove',moveHandle,true);
document.removeEventListener('mouseup',upHandle,true);
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.