面向对象的继承与修改(拖拽实例)

本文介绍了一种使用JavaScript实现元素拖拽效果的方法,并进一步扩展到带有边界限制的拖拽功能。通过对鼠标事件的监听和响应,使得指定的DOM元素能够跟随鼠标进行移动。此外,还提供了一个受限范围内的拖拽实例,确保元素不会移出可视区域。

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

window.onload = function () {
    new Drag("div1");
    new LimiteDrag("div12");
};

/////////////正常的没有限制范围的Drag函数////////////////////

function Drag(id) {
    this.oDiv = document.getElementById(id);
    this.disX = 0;
    this.disY = 0;
    var _this = this;
    this.oDiv.onmousedown = function(){
        _this.fnDown();
    };
};
Drag.prototype.fnDown = function(ev) {
    var ev = ev || window.event;
    var _this = this;
    this.disX = ev.clientX - this.oDiv.offsetLeft;
    this.disY = ev.clientY - this.oDiv.offsetTop;
    document.onmousemove = function(){
        _this.fnMove();
    };
    document.onmouseup = function(){
        _this.fnUp();
    };
};
Drag.prototype.fnMove = function(ev) {
    var ev = ev || window.event;
    this.oDiv.style.left = ev.clientX - this.disX + "px";
    this.oDiv.style.top = ev.clientY - this.disY + "px";
};
Drag.prototype.fnUp = function() {
    document.onmousemove = document.onmouseup = null;
};


/////////继承Drag对象,并添加限制范围的方法,变成新的LimiteDrag函数///////////

function LimiteDrag(id) {
    Drag.call(this,id);   // 第一步:执行Drag函数,通过Call(this)来改变this指向
};

for(var i in Drag.prototype){  // 第二步:浅拷贝,拷贝Drag上面所有的原型方法
    LimiteDrag.prototype[i] = Drag.prototype[i];
};

LimiteDrag.prototype.fnMove = function(ev) { // 第三步:覆盖并改变从Drag上面拷贝过来的fnMove方法
    var ev = ev || window.event;
    var l = ev.clientX - this.disX;
    var t = ev.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";
};

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值