用原生js实现了一个简单的拖拽功能。
e = e || window.event; 是为了兼容IE,因为IE的event是用window.event;
另外在IE早期版本可能就需要换用attachElement,并且事件前需要加on,所以也写了一个添加事件的兼容函数。删除事件也是。
<!doctype> <html> <head> <style> body { height: 200%; } #box { position: absolute; top: 50px; left: 50; width: 50px; height: 50px; background-color: red; } </style> <script type="text/javascript"> var x = 0, y = 0; window.onload = function() { var box = document.getElementById("box"); addEventHandler(box, "mousedown", dragDown); addEventHandler(document, "mousedown", docDragDown); } function getEvent(e) { return e || window.event; } function addEventHandler(obj, type, func) { if (window.attachEvent) { obj.attachEvent("on" + type, func); } else if (window.addEventListener) { obj.addEventListener(type, func); } else console.log ("add event error"); } function removeEventHandler(obj, type, func) { if (window.detachEvent) { obj.detachEvent("on" + type, func); } else if (window.removeEventListener) { obj.removeEventListener(type, func); } else console.log ("remove event error"); } //本来想实现滚动的时候被移动的对象也能够跟着滚动,但实现效果不佳,所以就没进一步实现了。 function getScrollEventType() { if (document.onmousewheel !== undefined) { return "mousewheel"; } else { return "DOMMouseScroll"; } } function dragDown(e) { addEventHandler(document, "mousemove", dragMove); addEventHandler(document, "mouseup", dragUp); var scrollType = getScrollEventType(); addEventHandler(document, scrollType, dragMove); } function docDragDown(e) { e = getEvent(e); var box = document.getElementById("box"); x = e.clientX - box.offsetLeft; //记录鼠标和被移动对象的初始偏移位置 y = e.clientY - box.offsetTop; } function dragMove(e) { e = getEvent(e); var box = document.getElementById("box"); box.style.left = e.clientX - x + "px"; box.style.top = e.clientY - y + "px"; } function dragUp(e) { var box = document.getElementById("box"); box.style.left = e.clientX - x + "px"; box.style.top = e.clientY - y + "px"; removeEventHandler(document, "mousemove", dragMove); removeEventHandler(document, "mouseup", dragUp); } </script> </head> <body> <div id="box"></div> </body> </html>