利用js原型继承实现拖拽效果。

<style>
        div{width: 100px;height: 100px;position: absolute;left:0;}
        #box1{background:red;top:0;}
        #box2{background:blue;top:130px;}
    </style>
</head>



<body>
    <div id="box1"></div>
    <div id="box2"></div>
</body>



<script>
    function Drag(ele){
        this.ele = ele;
        this.addEvent();
    }
    Drag.prototype.addEvent = function(){
        var that = this;
        this.ele.onmousedown = function(eve){
            that.downE = eve || window.event;
            document.onmousemove = function(eve){
                that.moveE = eve || window.event;
                that.move();
            }
            document.onmouseup = function(){
                that.up();
            }
        }
    }
    Drag.prototype.move = function(){
        this.ele.style.left = this.moveE.clientX - this.downE.offsetX + "px";
        this.ele.style.top = this.moveE.clientY - this.downE.offsetY + "px";
    }
    Drag.prototype.up = function(){
        document.onmousemove = null;
    }
    // 虽然都是拖拽,但是一个有边界限定,另一个没有边界限定
    function SmallDrag(ele){
        Drag.call(this, ele)
    }
    for(var i in Drag.prototype){
        SmallDrag.prototype[i] = Drag.prototype[i];
    }
    SmallDrag.prototype.move = function(){
        let l = this.moveE.clientX - this.downE.offsetX;
        let t = this.moveE.clientY - this.downE.offsetY;
        if(l<0) l=0;
        if(t<0) t=0;
        this.ele.style.left = l + "px";
        this.ele.style.top = t + "px";
    }
    var obox1 = document.getElementById("box1");
    var obox2 = document.getElementById("box2");
    new Drag(obox1);
    new SmallDrag(obox2);
    </script>
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值