一、建立一個div,並簡單設置樣式javascript
<!DOCTYPE html> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title></title> <style type="text/css"> #div1 { width: 150px; height: 150px; background-color: yellow; position: absolute; } </style> </head> <body> <div id="div1"></div> </body> </html>
二、面向過程的方式實現拖拽功能css
<script type="text/javascript"> window.onload = function () { var oDiv = document.getElementById("div1"); oDiv.onmousedown = function (e) { var oEvent = e || event; var divX = oEvent.clientX - oDiv.offsetLeft; var divY = oEvent.clientY - oDiv.offsetTop; document.onmousemove = function (e) { var oEvent = e || event; oDiv.style.left = oEvent.clientX - divX + "px"; oDiv.style.top = oEvent.clientY - divY + "px"; }; document.onmouseup = function () { document.onmousemove = null; document.onmouseup = null; } }; }; </script>
三、面向對象方式實現html
<script type="text/javascript"> window.onload = function () { new Drag("div1"); }; function Drag(id) { var _this = this;//保存this,指的是Drag,當 new Drag("div1");this變成了div1 this.divX = 0; this.divY = 0; this.oDiv = document.getElementById(id); this.oDiv.onmousedown = function (e) { _this.fnDown(e); return false;
}; } Drag.prototype.fnDown = function (e) { var _this = this; var oEvent = e || event; this.divX = oEvent.clientX - this.oDiv.offsetLeft; this.divY = oEvent.clientY - this.oDiv.offsetTop; document.onmousemove = function (e) { _this.fnMove(e); }; document.onmouseup = function () { _this.fnUp(); }; } Drag.prototype.fnMove = function (e) { var oEvent = e || event; this.oDiv.style.left = oEvent.clientX - this.divX + "px"; this.oDiv.style.top = oEvent.clientY - this.divY + "px"; } Drag.prototype.fnUp = function () { document.onmousemove = null; document.onmouseup = null; } </script>
四、在建立一個divjava
<style type="text/css"> #div1, #div2 { width: 150px; height: 150px; background-color: yellow; position: absolute; } #div2 { width: 150px; height: 150px; position: absolute; background-color: green; } </style> <body> <div id="div1">普通拖拽</div> <div id="div2">限制範圍拖拽</div> </body>
五、限制範圍的拖拽功能直接繼承Dragapp
function LimitDrag(id) {
Drag.call(this, id);//LimitDrag繼承Drag
}
//這樣寫,避免擴展LimitDrag時影響Drag
for (var i in Drag.prototype) {
LimitDrag.prototype[i] = Drag.prototype[i];
}
<script type="text/javascript"> window.onload = function () { new Drag("div1"); new LimitDrag("div2"); }; </script>
六、擴展LimitDragui
//擴展LimitDrag,其實就是重寫了父類的fnMove方法 LimitDrag.prototype.fnMove = function (e) { var oEvent = e || event; var l = oEvent.clientX - this.divX; var t = oEvent.clientY - this.divY; if (l < 0) { l = 0; } else if (l > document.documentElement.clientWidth - this.oDiv.offsetWidth) { l = document.documentElement.clientWidth - this.oDiv.offsetWidth; } this.oDiv.style.left = l + "px"; this.oDiv.style.top = t + "px"; }
注:apply,call都是改變this對象this
參考資料:http://v.pps.tv/play_362R1J.htmlspa