一、思路
1 、先用面向?qū)ο蟮姆椒ò淹献У墓δ軐崿F(xiàn)
(1)
先要我們所需要拖拽的物體 DragBox(boxId)
(2)
然后在得到我們物體的節(jié)點屬性this.ele = document.getElementById(boxId);
(3)將我們物體的三種方法start、move、stop用對象形式表達出來,為了不占用多的空間我們使用DragBox.prototype.
(4)因為物體一開始創(chuàng)建就具有拖拽的能力,所以,我們一開始就設(shè)置按下的函數(shù)this.ele.onmousedown
以下是我們的拖拽代碼:
function Dray(boxId){
if (boxId == undefined)
{
return
}
this.elem = document.getElementById(boxId);
var self = this
this.elem.onmousedown = function (e){
e.preventDefault();
self.dateX = e.clientX - self.elem.offsetLeft;
self.dateY = e.clientY - self.elem.offsetTop;
self.start();
document.onmouseup = function (){
self.stop();
}
}
}
Dray.prototype.start = function (){
var self = this;
document.onmousemove = function (e){
var x = e.clientX - self.dateX;
var y = e.clientY - self.dateY;
self.move(x, y)
}
}
Dray.prototype.move = function (x , y){
var self = this
self.elem.style.left = x + "px"
self.elem.style.top = y + "px"
}
Dray.prototype.stop = function (){
document.onmousemove = null
}
2 、 我們需要重新創(chuàng)建一個html然后將我們的之前下的拖拽代碼鏈接進來;再在body里面設(shè)置你所需要拖拽的物體。<script src="DragBox.js"></script>
<style>
div {
width: 100px;
height: 100px;
background: red;
position: absolute;
}
#box2 {
background: green;
}
#box3 {
background: blue;
}
</style>
<div id="box1"></div>
<div id="box2"></div>
<div id="box3"></div>
3、 我們可以用面向?qū)ο笾械睦^承來實現(xiàn)拖拽
(1)繼承之前拖拽功能的屬性
function DragBoxTaxt(boxId){
DragBox.call(this,boxId);
}
(2) 繼承之前拖拽功能的方法
DragBoxText.prototype = new DragBox();
(3)還可以修改之前拖拽功能的方法
DragBoxText.prototype.move = function(x, y) {
// this.ele.style.left = x + "px";
// this.ele.style.top = y + "px";
DragBox.prototype.move.call(this, x, y)
this.ele.innerHTML = x + ", " + y;
}
(4)創(chuàng)建對象讓他們具有拖拽的功能;
new DragBoxText("box1");
new DragBoxText("box2");
new DragBoxText("box3");
二 、 難點
(1)修改move方法是用到的DragBox.prototype.move.call(this, x, y)
這是是我們有搞懂滴!
(2) 在封裝的之前拖拽的代碼中if (boxId == undefined){return}