虽然网上又很多实现方法,但是还是需要理解拖放原理。通过绑定onmousedown,onmousemove.onmouseup事件来实现层拖放位置变化,这只是很简单实现,可以去换个方法去实现。
<!DOCTYPE html> <html> <head> <title>demo</title> <style> .drag1 , .drag2{ position:relative; width:200px; height:200px; line-height: 200px; text-align: center; vertical-align: middle; border-radius: 5px; border:1px solid red; } </style> </head> <body> <div id="drag1" class="drag1"> drag layer </div> </body> <script> // drag and drap class function DND(el){ _startX = 0; // mouse starting positions _startY = 0; _offsetX = 0; // current element offset _offsetY = 0; _dragElement = el; // needs to be passed from OnMouseDown to OnMouseMove _oldZIndex = 0; // we temporarily increase the z-index during drag } DND.prototype = { init : function(){ var _this = this; //replace with adeventListeners or attachEvent document.onmousedown = function(e){_this.onMouseDown(e)}; document.onmouseup = function(e){_this.onMouseUp(e)}; }, onMouseDown: function(e){ var even = e ? e : window.event; var target = e.target ? e.target : e.srcElement; if(e.button == 1 || e.button == 0){ _startX = even.clientX; _startY = even.clientY; _offsetX = this.parseMumber(target.style.left); _offsetY = this.parseMumber(target.style.top); _oldZindex = target.style.zIndex; _dragElement = target; //replace with adeventListeners or attachEvent document.onmousemove = this.onMouseMove; // cancel out any text selections document.body.focus(); // prevent text selection in IE document.onselectstart = function () { return false; }; // prevent IE from trying to drag an image target.ondragstart = function() { return false; }; return false; } }, onMouseMove: function(e){ var e = e ? e : window.event; _dragElement.style.left = (_offsetX + e.clientX - _startX) + 'px'; _dragElement.style.top = (_offsetY + e.clientY - _startY) + 'px'; _dragElement.style.cursor ="move"; }, onMouseUp: function(e){ if(_dragElement){ //replace with adeventListeners or attachEvent document.onmousemove = null; document.onselectstart = null; _dragElement.ondragstart = null; _dragElement.style.cursor =""; _dragElement = null; } }, parseMumber: function(value){ var n = parseInt(value); return isNaN(n) ? 0 : n; } }; var dd1 = new DND(document.getElementById("drag1")).init(); </script> </html>
参考:
http://www.cnblogs.com/Godblessyou/archive/2008/05/14/1196746.html
http://www.webreference.com/programming/javascript/mk/column2/
http://luke.breuer.com/tutorial/javascript-drag-and-drop-tutorial.aspx
http://www.quirksmode.org/js/dragdrop.html