#用面向对象编写拖拽
###用面向过程编写拖拽
```
<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的选项卡组件开发