js 拖拽實現面向對象
阿新 • • 發佈:2018-05-13
oct utf-8 xhtml bsp AC name java prototype new
// JavaScript Document /*構造函數*/ function Drag(id){ this.disX = 0; this.disY = 0; this.oDiv = document.getElementsByTagName(id)[0]; var _this = this; this.oDiv.onmousedown = function(ev){ _this.fnDown(ev); return false; }; } Drag.prototype.fnDown= function(ev){ var oEvent = ev || event; this.disX = oEvent.clientX - this.oDiv.offsetLeft; this.disY = oEvent.clientY - this.oDiv.offsetTop; var _this = this; document.onmouseover = function(ev){ _this.fnMove(ev); }; document.onmouseup= function(){ _this.fnUp(ev); }; } Drag.prototype.fnMove = function(ev){ var ev = ev || event; this.oDiv.style.left = ev.clientX - this.disX+‘px‘; this.oDiv.style.top = ev.clientY - this.disY+‘px‘; } Drag.prototype.fnUp = function(){ document.onmouseover= document.onmouseup = null; }
// JavaScript Document function LimateDrag(id){ Drag.call(this,id); //繼承屬性 } //繼承方法 for(var i in Drag.prototype){ LimateDrag.prototype[i] = Drag.prototype[i] } LimateDrag.prototype.fnMove = function(ev){ var ev = ev || event; var l = ev.clientX - this.disX; var t = ev.clientY - this.disY; if(l < 0){ l = 0; }else if(l >= document.documentElement.clientWidth-this.oDiv.offsetWidth ){ l = document.documentElement.clientWidth-this.oDiv.offsetWidth; } if(t < 0){ t = 0; }else if(t >= document.documentElement.clientHeight-this.oDiv.offsetHeight){ t = document.documentElement.clientHeight-this.oDiv.offsetHeight; } this.oDiv.style.left = l+‘px‘; this.oDiv.style.top = t+‘px‘; }
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> <html xmlns="http://www.w3.org/1999/xhtml"> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <title>無標題文檔</title> <style> div{width:100px;height:100px;background:red;position:absolute;left:0;top:0;} </style> <script src =‘Drag.js‘></script> <script src =‘LimateDrag.js‘></script> <script> window.onload = function(){ new LimateDrag(‘div‘); }; </script> </head> <body> <div></div> </body> </html>
js 拖拽實現面向對象