JS面向对象实现简单拖拽心得

一、思路

1 、先用面向对象的方法把拖拽的功能实现

(1)
           先要我们所需要拖拽的物体 DragBox(boxId)
(2)
          然后在得到我们物体的节点属性this.ele = document.getElementById(boxId);
(3)将我们物体的三种方法start、move、stop用对象形式表达出来,为了不占用多的空间我们使用DragBox.prototype.
  (4)因为物体一开始创建就具有拖拽的能力,所以,我们一开始就设置按下的函数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 、 我们需要重新创建一个html然后将我们的之前下的拖拽代码链接进来;再在body里面设置你所需要拖拽的物体。


  
    
3、 我们可以用面向对象中的继承来实现拖拽
(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)创建对象让他们具有拖拽的功能;
new DragBoxText("box1");
new DragBoxText("box2");
new DragBoxText("box3");

二 、 难点

(1)修改move方法是用到的DragBox.prototype.move.call(this, x, y)
这是是我们有搞懂滴!
(2) 在封装的之前拖拽的代码中if (boxId == undefined){return}

你可能感兴趣的:(JS面向对象实现简单拖拽心得)