zoukankan      html  css  js  c++  java
  • 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>

  • 相关阅读:
    MySQL-02 数据表管理
    MySQL-01 MySQL数据库安装指南
    Linux-04 Linux中Tomcat和MySQL的安装
    Linux-03 Linux下的tar命令
    Linux-02 Linux常用命令
    Linux-01 虚拟机Linux的安装
    从服务器下载图片
    WPF Radio组的绑定
    使用缓存的9大误区(下)转载
    使用缓存的9大误区(上)转载
  • 原文地址:https://www.cnblogs.com/xiaohuochai/p/6582779.html
Copyright © 2011-2022 走看看