拖拽是理解「封裝—複用—繼承」的絕佳素材。本文先寫出一個帶邊界約束的 Drag 類,再透過繼承派生出受限版本。
<html xmlns="https://www.w3.org/1999/xhtml">
<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 Drag("div2");
};
function Drag(id) {
var _this=this;
this.oDiv=document.getElementById(id);
this.disX=0;
this.disY=0;
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;
var l=oEvent.clientX-this.disX;
var t=oEvent.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';
};
Drag.prototype.fnUp=function() {
document.onmousemove=null;
document.onmouseup=null;
};
</script>
</head>
<body>
<div id="div1"></div>
<div id="div2"></div>
</body>
</html>
disX/disY 記錄滑鼠與元素左上角的相對距離,拖動時用 clientX - disX 還原左上角座標,避免元素「跳」到滑鼠底下。mousemove 與 mouseup 綁在文件層級,滑鼠即使移出元素範圍也不會中斷拖拽;fnUp 負責及時卸載,防止事件洩漏。clientWidth/Height 減去元素 offsetWidth/Height,把元素鎖在可視區域內。如果要在拖拽基礎上再加限制(例如限定在某個容器內水平移動),不必複製代碼,繼承即可:
function LimitDrag(id){
Drag.call(this,id); // 繼承實例屬性
for(var i in Drag.prototype){
LimitDrag.prototype[i]=Drag.prototype[i];
}
}
Drag.call(this, id) 借用父類構造函數完成屬性初始化,第二個循環則把父類原型上的方法逐一複製到子類原型。這種寫法簡單直觀,是理解原型鏈的入門方式;若追求更嚴謹的繼承鏈,可以再研究原型式繼承與 Object.create 的組合。
延伸閱讀:本站《JavaScript 面向對象入門教程》《JavaScript 動畫特效與技巧匯總》等專題。