JavaScript面向对象简单拖拽

本文介绍了一种使用JavaScript实现的拖拽效果,包括普通的拖拽功能和限制范围内的拖拽功能。通过简单的HTML和CSS布局,结合JavaScript代码,实现了元素在网页上的自由拖动及限定区域内的拖动。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #div1{
            width: 200px;
            height: 200px;
            position: absolute;
            background: red;
        }
        #div2{
            width: 200px;
            height: 200px;
            position: absolute;
            background: green;
        }
    </style>
    <script src="面向对象拖拽.js"></script>
    <script src="限制范围拖拽(继承).js"></script>
    <script>
        window.onload=function () {
            new Drag('div1');
            new LimitDrag('div2')
        }
    </script>
</head>
<body>
    <div id="div1">普通拖拽</div>
    <div id="div2">限制范围拖拽</div>
</body>
</html>
//普通拖拽
function Drag(id) {
    this.oDiv=document.getElementById(id)
    this.dis_x=0;
    this.dis_y=0;
    var _this=this;
    this.oDiv.onmousedown=function (ev) {
        _this.fnDown(ev)
    }
}
Drag.prototype.fnDown=function (ev) {
    var oEvent=ev||event;
    this.dis_x=oEvent.clientX-this.oDiv.offsetLeft;
    this.dis_y=oEvent.clientY-this.oDiv.offsetTop;
    var _this=this;
    document.onmousemove=function (ev) {
        _this.fnMove(ev)
    }
    document.onmouseup=function (ev) {
        _this.fnUp();
    }
}
Drag.prototype.fnMove=function (ev) {
    var oEvent=ev||event;
    this.oDiv.style.left=oEvent.clientX-this.dis_x+'px';
    this.oDiv.style.top=oEvent.clientY-this.dis_y+'px';
}
Drag.prototype.fnUp=function () {
    document.onmousedown=null;
    document.onmousemove=null;
}

//限制范围的拖拽
function LimitDrag(id) {
    Drag.call(this,id);
}
for (var i in Drag.prototype)
{
    LimitDrag.prototype[i]=Drag.prototype[i]
}
LimitDrag.prototype.fnMove=function (ev) {
    var oEvent=ev||event;
    var l=oEvent.clientX-this.dis_x;
    var t=oEvent.clientY-this.dis_y;
    if (l<0)
    {
        l=0
    }
    else if (l>document.documentElement.clientWidth-this.oDiv.offsetWidth)
    {
        l=document.documentElement.clientWidth-this.oDiv.offsetWidth
    }
    this.oDiv.style.left=l+'px';
    if (t<0)
    {
        t=0
    }
    else if (t>document.documentElement.clientHeight-this.oDiv.offsetHeight)
    {
        t=document.documentElement.clientHeight-this.oDiv.offsetHeight
    }
    this.oDiv.style.top=t+'px';
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值