下面的頁面中放了兩個div,可以通過滑鼠拖拽這兩個元素到任意位置。
實現該效果的HTML頁面代碼如下所示:
<script type="text/javascript" src="js/mylib.js"></script> <script type="text/javascript"> window.onload = function() { var obj1 = createDraggableObject(); var obj2 = createDraggableObject(); obj1.init($('xixi')); obj2.init($('haha')); }; </script> Fuck! Shit!
外部JavaScript檔案代碼如下所示:
/** * 根據id擷取頁面元素 * @param id * @returns {HTMLElement} */function $(id) { return document.getElementById(id);}/** * 建立可拖拽對象的Factory 方法 */function createDraggableObject() { return { obj: null, left: 0, top: 0, oldX: 0, oldY: 0, isMouseLeftButtonDown: false, init: function (obj) { this.obj = obj;var that = this; this.obj.onmousedown = function (args) { var evt = args || event; this.style.zIndex = 100; that.isMouseLeftButtonDown = true; that.oldX = evt.clientX; that.oldY = evt.clientY;if (this.currentStyle) { that.left = parseInt(this.currentStyle.left); that.top = parseInt(this.currentStyle.top); } else { var divStyle = document.defaultView.getComputedStyle(this, null); that.left = parseInt(divStyle.left); that.top = parseInt(divStyle.top); } }; this.obj.onmousemove = function (args) { that.move(args || event); }; this.obj.onmouseup = function () { that.isMouseLeftButtonDown = false; this.style.zIndex = 0; }; }, move: function (evt) { if (this.isMouseLeftButtonDown) { var dx = parseInt(evt.clientX - this.oldX); var dy = parseInt(evt.clientY - this.oldY); this.obj.style.left = (this.left + dx) + 'px'; this.obj.style.top = (this.top + dy) + 'px'; } } };}