心路历程:
老师给我们先写好了一个简易拖拽的封装。一步一步给我们讲解,可谓是幸苦的不行,然而重点不在封装,在细节细节。
代码总览:
<!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>
简易封装:
function DragBox(boxId) {
if (boxId == undefined) {
return;
}
// 属性
this.ele = document.getElementById(boxId);
var self = this;
// 因为物体一开始创建就具有拖拽的能力,所以,一开始就进行按下的设置
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: 移动
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;
}
然后引入封装写出要移动的东西。
sript src="DragBox.js"></script> 引入封装
移动的元素自己设定!
引用封包就可以拖拽了。。。
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
new DragBoxText("box1");
new DragBoxText("box2");
new DragBoxText("box3");
下来这个就是难点了
在移动的物体上加上坐标,老师一说当场就懵逼了。
老师吧代码敲完是一个懵逼的我上线。
吧细节讲完才稍微领悟那么一丢丢。
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;
}
网友评论