使用构造函数实现拖拽

*{
    padding: 0;
    margin: 0;
}
button {
    display: block;
    border: none;
    outline: none;
    width: 200px;
    height: 50px;
    line-height: 50px;
    font-size: 24px;
    color: red;
    background: #aaa;
    border-radius: 20%;
    margin: 20px auto;
}
div {
    position: absolute;
    border: 1px solid #000;
    top: 0;
    left: 0;
}
<button>叮!!!</button>
var btns=document.getElementsByTagName('button')[0];
var bodys=document.getElementsByTagName('body')[0];
function Box() {
    this.width=100;
    this.height=100;
    this.creatBox();
}
Box.prototype.ranColor=function(){
    return Math.floor(Math.random()*255);
}
Box.prototype.creatBox=function () {
    this.ele=document.createElement('div');
    this.ele.style.cssText='width:'+this.width+'px;height:'+this.height+'px;background:rgb('+this.ranColor()+","+this.ranColor()+","+this.ranColor()+");";
    bodys.append(this.ele);
    this.resize();
}
Box.prototype.resize=function () {
    var that=this;
    this.ele.onmousedown=function (ev) {
        var boxX=ev.clientX-this.offsetLeft;
        var boxY=ev.clientY-this.offsetTop;
        document.onmousemove=function (ev) {
            that.ele.style.cssText+='left:'+(ev.clientX-boxX)+'px;top:'+(ev.clientY-boxY)+'px';
        }
        document.onmouseup=function () {
            document.onmouseup=document.onmousemove=null;
        }
    }
}
btns.onclick=function () {
    var a=new Box();
}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值