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>

  • 相关阅读:
    Ubuntu 装JDK
    U盘文件夹被病毒隐藏,且不能取消解决办法
    wireshark: there are no interfaces on which a capture can be done
    [转]Ubuntu 常用快捷键10个
    恢复被win7覆盖的Ubuntu Grub
    U盘安装Win7 64位
    荣耀3X畅玩版狙击红米note!
    Secret and Whisper
    360 chrome不能登录Google账户
    周鸿祎仍想做手机
  • 原文地址:https://www.cnblogs.com/xiaohuochai/p/6582779.html
Copyright © 2011-2022 走看看