#用面向對象編寫拖拽
###用面向過程編寫拖拽
```
<style>
#div1{ width: 100px; height: 100px; background: red; position: absolute; }
</style>
<script>
window.onload = function () {
var oDiv = document.getElementById('div1');
var disX = 0;
var disY = 0;
oDiv.onmousedown = function(ev){
var ev = ev || window.event;
disX = ev.clientX - oDiv.offsetLeft;
disY = ev.clientY - oDiv.offsetTop;
document.onmousemove = function(ev){
var ev = ev || window.event;
oDiv.style.left = ev.clientX - disX + 'px';
oDiv.style.top = ev.clientY - disY + 'px';
};
document.onmouseup = function(){
document.onmousemove = null;
document.onmouseup = null;
};
return false;
};
};
</script>
<div id="div1"></div>
```
###普通方法變型
```
var oDiv = null;
var disX = 0;
var disY = 0;
window.onload = function () {
oDiv = document.getElementById('div1');
init();
};
function init(){
oDiv.onmousedown = fnDown;
}
function fnDown(ev){
var ev = ev || window.event;
disX = ev.clientX - oDiv.offsetLeft;
disY = ev.clientY - oDiv.offsetTop;
document.onmousemove = fnMove;
document.onmouseup = fnUp;
return false;
}
function fnMove(ev){
var ev = ev || window.event;
oDiv.style.left = ev.clientX - disX + 'px';
oDiv.style.top = ev.clientY - disY + 'px';
}
function fnUp(){
document.onmousemove = null;
document.onmouseup = null;
}
```
###用面向對象編寫拖拽
```
window.onload = function(){
var d1 = new Drag('div1');
d1.init();
};
function Drag(id){
this.oDiv = document.getElementById(id);
this.disX = 0;
this.disY = 0;
}
Drag.prototype.init = function(){
var _this = this;
this.oDiv.onmousedown = function(ev){
var ev = ev || window.event;
_this.fnDown(ev);
return false;
};
};
Drag.prototype.fnDown = function(ev){
var _this = this;
this.disX = ev.clientX - this.oDiv.offsetLeft;
this.disY = ev.clientY - this.oDiv.offsetTop;
document.onmousemove = function(ev){
var ev = ev || window.event;
_this.fnMove(ev);
};
document.onmouseup = this.fnUp;
};
Drag.prototype.fnMove = function(ev){
this.oDiv.style.left = ev.clientX - this.disX + 'px';
this.oDiv.style.top = ev.clientY - this.disY + 'px';
};
Drag.prototype.fnUp = function(){
document.onmousemove = null;
document.onmouseup = null;
};
```
- 01 JS面向對象及組件開發
- 02 傳統的過程式編寫選項卡
- 03 用面向對象封裝通用選項卡
- 04 控制多個選項卡自動播放
- 05 用面向對象編寫拖拽
- 06 JS面向對象及組件開發
- 07 hasOwnProperty和constructor的使用
- 08 instanceof運算符的使用
- 09 利用toString做類型判斷
- 10 什么是面向對象的繼承
- 11 面向對象之拷貝繼承
- 12 編寫繼承的拖拽
- 13 繼承的其他形式之類式繼承
- 14 繼承的其他形式之原型繼承
- 15 組件開發是什么
- 16 給拖拽組件配置不同參數
- 17 封裝彈框組件
- 18 使用對象標記已彈出彈框
- 19 復雜組件開發之自定義事件
- 20 原生JS實現自定義事件
- 21 自定義事件實例
- 22 基于JQ的選項卡組件開發