zoukankan      html  css  js  c++  java
  • 继承案例_限制范围的拖拽

    Drag.js

    function Drag(id) {
        var _this = this;
        this.disX = 0;
        this.disY = 0;
        this.oDiv = document.getElementById(id);
        this.oDiv.onmousedown = function (ev) {
            _this.fnDown(ev);
        };
    }
    
    Drag.prototype.fnDown = function(ev) {
        var _this = this;
        var oEvent = ev||event;
        //鼠标距离减去物体位置
        this.disX = oEvent.clientX-this.oDiv.offsetLeft;
        this.disY = oEvent.clientY-this.oDiv.offsetTop;
        document.onmousemove = function (ev) {
            _this.fnMove(ev);
        };
        document.onmouseup = function () {
            _this.fnUp();
        };
    };
    Drag.prototype.fnMove = function(ev) {//限制范围添加到这里
        var oEvent = ev||event;
        this.oDiv.style.left = oEvent.clientX-this.disX+'px';
        this.oDiv.style.top = oEvent.clientY-this.disY+'px';
    };
    Drag.prototype.fnUp =function() {
        document.onmousemove = null;
        document.onmouseup = null;
    }

    LimitDrag.js

    function LimitDrag(id) {
        //用构造函数伪装,继承属性
        Drag.call(this,id);
    }
    //用原型链继承方法
    for(var i in Drag.prototype){
        LimitDrag.prototype[i] = Drag.prototype[i];
    }
    LimitDrag.prototype.fnMove = function (ev) {//覆盖Drag.js里的方法。
        var oEvent = ev||event;
        var l = oEvent.clientX-this.disX;
        var t = oEvent.clientY-this.disY;
        if(l<0){
            l=0;
        }else if(l>document.documentElement.clientWidth-this.oDiv.offsetWidth){
            l=document.documentElement.clientWidth-this.oDiv.offsetWidth;
        }
        if(t<0){
            t=0;
        }else if(t>document.documentElement.clientHeight-this.oDiv.offsetHeight){
            t=document.documentElement.clientHeight-this.oDiv.offsetHeight;
        }
        this.oDiv.style.left =l +'px';
        this.oDiv.style.top = t+'px';
    }

    html

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title></title>
        <style>
            #div1{width:100px;height:100px;background-color:green;position:absolute;left:0;top:0;}
            #div2{width:100px;height:100px;background-color:red;position:absolute;right:0;top:0;}
        </style>
    </head>
    <body>
    <div id="div1"></div>
    <div id="div2"></div>
    </body>
    </html>
    <script type="text/javascript" src="Drag.js"></script>
    <script type="text/javascript" src="LimitDrag.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            new Drag("div1");
            new LimitDrag("div2");
        }
    </script>
  • 相关阅读:
    win10 创建安卓模拟器及启动的方法
    win10 virtualenv
    win10安装nodejs
    python模块打包方法
    win10 安装java
    git push后自动部署
    ubuntu配置无密码登录
    mysql while,loop,repeat循环,符合条件跳出循环
    centos 安装mysql密码修改后还是不能连接的原因
    查看SQLServer数据库信息的SQL语句
  • 原文地址:https://www.cnblogs.com/wang715100018066/p/6051945.html
Copyright © 2011-2022 走看看