心路歷程:
老師給我們先寫好了一個(gè)簡(jiǎn)易拖拽的封裝。一步一步給我們講解,可謂是幸苦的不行,然而重點(diǎn)不在封裝,在細(xì)節(jié)細(xì)節(jié)。
代碼總覽:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="Generator" content="EditPlus?">
<meta name="Author" content="">
<meta name="Keywords" content="">
<meta name="Description" content="">
<title>Document</title>
<style>
div {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
#box2 {
background: green;
}
#box3 {
background: blue;
}
</style>
</head>
<body>
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
<script src="DragBox.js"></script>
<script>
function DragBoxText(boxId) {
// 繼承 DragBox 的屬性
DragBox.call(this, boxId);
}
// 繼承 DragBox 的方法
DragBoxText.prototype = new DragBox();
// 修改了父親了的方法
DragBoxText.prototype.move = function(x, y) {
DragBox.prototype.move.call(this, x, y)
this.ele.innerHTML = x + ", " + y;
}
// 讓 box1 具備拖拽的能力
new DragBoxText("box1");
new DragBoxText("box2");
new DragBoxText("box3");
</script>
</body>
</html>
簡(jiǎn)易封裝:
function DragBox(boxId) {
if (boxId == undefined) {
return;
}
// 屬性
this.ele = document.getElementById(boxId);
var self = this;
// 因?yàn)槲矬w一開始創(chuàng)建就具有拖拽的能力,所以,一開始就進(jìn)行按下的設(shè)置
this.ele.onmousedown = function(e) {
self.detaX = e.clientX - self.ele.offsetLeft;
self.detaY = e.clientY - self.ele.offsetTop;
// 開始
self.start();
// 停止
document.onmouseup = function() {
self.stop();
}
}
}
方法1: 開始
DragBox.prototype.start = function() {
var self = this;
document.onmousemove = function(e) {
var x = e.clientX - self.detaX;
var y = e.clientY - self.detaY;
self.move(x, y)
}
}
方法2: 移動(dòng)
DragBox.prototype.move = function(x, y) {
var self = this;
self.ele.style.left = x + "px";
self.ele.style.top = y + "px";
}
方法3: 停止
DragBox.prototype.stop = function() {
document.onmousemove = null;
}
然后引入封裝寫出要移動(dòng)的東西。
sript src="DragBox.js"></script> 引入封裝
移動(dòng)的元素自己設(shè)定!
引用封包就可以拖拽了。。。
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
new DragBoxText("box1");
new DragBoxText("box2");
new DragBoxText("box3");
下來(lái)這個(gè)就是難點(diǎn)了
在移動(dòng)的物體上加上坐標(biāo),老師一說(shuō)當(dāng)場(chǎng)就懵逼了。
老師吧代碼敲完是一個(gè)懵逼的我上線。
吧細(xì)節(jié)講完才稍微領(lǐng)悟那么一丟丟。
function DragBoxText(boxId) {
// 繼承 DragBox 的屬性
DragBox.call(this, boxId);
}
// 繼承 DragBox 的方法
DragBoxText.prototype = new DragBox();
DragBox.prototype.move.call(this, x, y)這里可以寫成
this.ele.style.left = x + "px";
this.ele.style.top = y + "px";
// 修改了父親了的方法
DragBoxText.prototype.move = function(x, y) {
DragBox.prototype.move.call(this, x, y)
this.ele.innerHTML = x + ", " + y;
}