javascript面向对象系列第五篇——拖拽的实现

前面的话

  在之前的博客中,拖拽的实现使用了面向过程的写法。本文将以面向对象的写法来实现拖拽

 

写法

<style>
.test{height: 50px;width: 50px;background-color: pink;position:absolute;}
#test2{left:60px;background-color: lightblue;}
</style>
</head>
<body>
<div id="test1" class="test"></div>
<div id="test2" class="test"></div>
<script>
function Drag(obj){
    this.obj= obj;
}
Drag.prototype.init = function(){
    var that = this;
    this.obj.onmousedown = function(e){
        e = e || event;
        that.fnDown(e);
        document.onmousemove = function(e){
            e = e || event;
            that.fnMove(e);
        }
        document.onmouseup = function(){
            that.fnUp();
        }
        return false;
    }
};
Drag.prototype.fnDown = function(e){
    this.disX = e.clientX - this.obj.offsetLeft;
    this.disY = e.clientY - this.obj.offsetTop;
}
Drag.prototype.fnMove = function(e){
    this.obj.style.left = e.clientX - this.disX + 'px';
    this.obj.style.top = e.clientY - this.disY + 'px';
}
Drag.prototype.fnUp = function(){
    document.onmousemove = document.onmouseup = null;
}
function ChildDrag(obj){
    Drag.call(this,obj);
}
if(!Object.create){
  Object.create = function(proto){
    function F(){};
    F.prototype = proto;
    return new F;
  }
}
ChildDrag.prototype = Object.create(Drag.prototype);
ChildDrag.prototype.constructor = ChildDrag;
var drag1 = new Drag(test1);
drag1.init();
ChildDrag.prototype.fnMove = function(e){
    var L = e.clientX - this.disX;
    var T = e.clientY - this.disY;
    if(L < 0){L = 0;}
    if(T < 0){T = 0;}
    this.obj.style.left = L + 'px';
    this.obj.style.top = T + 'px';    
}
var drag2 = new ChildDrag(test2);
drag2.init();
</script>

 

posted @ 2017-03-19 22:39  小火柴的蓝色理想  阅读(1097)  评论(0编辑  收藏  举报