本文整理自己實作拖拽功能時,以原型方式封裝所延伸出的幾個關鍵問題,並附上可拖曳、可限制範圍的完整範例。
for(var i in Drag.prototype) {
LimitDrag.prototype[i] = Drag.prototype[i]; // 逐個複製:子類別日後修改不會影響父類別
}
LimitDrag.prototype = Drag.prototype; // 直接指向同一個原型:子類別一改,父類別跟著變
換句話說,若打算在子類別裡覆寫 fnMove 卻不希望污染父類別,就必須用 for-in 逐個拷貝。
<html>
<head>
<style>
#div1 {width:100px; height:100px; background:red; position:absolute;}
#div2 {width:100px; height:100px; background:yellow; position:absolute;}
</style>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>拖拽--面向對象</title>
<script>
window.onload=function() {
new Drag('div1');
new LimitDrag('div2');
}
function Drag(id) {
var _this=this;
this.disx=0;
this.disy=0;
this.oDiv=document.getElementById(id);
this.oDiv.onmousedown=function(ev){
_this.fnDown(ev);
return false;
}
};
Drag.prototype.fnDown=function(ev) {
var _this=this;
var oEvent=ev||event;
this.disx=oEvent.clientX-this.oDiv.offsetLeft;
this.disy=oEvent.clientY-this.oDiv.offsetTop;
document.onmousemove=function(ev){ _this.fnMove(ev); }
document.onmouseup=function(){ _this.fnUp(); }
};
Drag.prototype.fnMove=function(ev) {
var oEvent=ev||event;
this.oDiv.style.left=oEvent.clientX-this.disx+'px';
this.oDiv.style.top=oEvent.clientY-this.disy+'px';
};
Drag.prototype.fnUp=function() {
document.onmousemove=null;
document.onmouseup=null;
};
function LimitDrag(id) {
Drag.call(this,id);
}
for(var i in Drag.prototype) {
LimitDrag.prototype[i]=Drag.prototype[i];
}
LimitDrag.prototype.fnMove=function(ev) {
var oEvent=ev||event;
var l=oEvent.clientX-this.disx;
var t=oEvent.clientY-this.disy;
if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth) {
l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
} else if(l<0) { l=0; }
if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight) {
t=document.documentElement.clientHeight-this.oDiv.offsetHeight;
} else if(t<0) { t=0; }
this.oDiv.style.left=l+'px';
this.oDiv.style.top=t+'px';
}
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
LimitDrag 只覆寫了 fnMove 加入邊界判斷,其餘行為完全沿用 Drag,這正是原型繼承帶來的複用價值。以上就是本文全部內容,希望對你的學習有所幫助。