面向对象的拖拽
1、创建一个div,并简单设置样式
<!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>
2、面向过程的方式实现拖拽功能
<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>
3、面向对象方式实现
<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>
4、在创建一个div
<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>
5、限制范围的拖拽功能直接继承Drag
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>
6、扩展LimitDrag
//扩展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对象
参考资料:http://v.pps.tv/play_362R1J.html