SOURCE

console 命令行工具 X clear

                    
>
console
window.onload = function(){
    let d1 = new Drag();
    d1.init('div1');
    let d2 = new Drag();
    d2.init('div2');
    let d3 = new Drag();
    d3.init('div3');
    let d4 = new Drag();
    d4.init('div4');
}

// Drag构造函数
function Drag(){
    this.obj = null;
    this.disX = 0;
    this.disY = 0;
    this.settings = {

    }
}

Drag.prototype.init = function(id,opt){
    this.obj = document.getElementById(id);
    var _this = this;
    this.obj.onmousedown = function(ev){
        var ev = ev || window.event;
        _this.toDown(ev);
        document.onmousemove = function(ev){
            var ev = ev || window.event;
            _this.toMove(ev);
        }
        document.onmouseup = function(){
            _this.toUp();
        }
    }   
}

// 拖拽三大事件
// 1.鼠标按下
Drag.prototype.toDown = function(ev){
    this.disX = ev.clientX - this.obj.offsetLeft;
    this.disY = ev.clientY - this.obj.offsetTop;
    // 元素被选中的时候的样式的添加
    this.obj.classList.add('checkdiv');
}

// 2.鼠标移动
Drag.prototype.toMove = function(ev){
    this.obj.style.left = ev.clientX - this.disX + 'px';
    this.obj.style.top = ev.clientY - this.disY + 'px';
}

// 3.鼠标抬起
Drag.prototype.toUp = function(){
    document.onmousedown = null;
    document.onmousemove = null;
    //元素选中结束时候的样式移除
    this.obj.classList.remove('checkdiv')
}

// 元素生成事件按钮

let btn = document.querySelector('input[type="button"]');
// console.log(btn);

// 为按钮绑定事件
let i = 5;//新生成的按钮个数
btn.onclick = function(){
    let newDiv = [];
    newDiv[i] = document.createElement('div');
    newDiv[i].classList.add('div');
    newDiv[i].setAttribute('id','div' + i);
    newDiv[i].style.top = i + 50 + 'px';
    // alert('事件触发了');
    document.body.appendChild(newDiv[i]);
    let d = [];
    d[i] = new Drag();
    d[i].init('div'+i);
    i++;
}
<!-- 拖拽组件开发 -->
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
<input type="button" value="CREATE" />
div{
    width: 100px;
    height: 80px;
    position: absolute;
    border: 1px solid #c994bd;
    cursor: move;
    border-radius: 10px 20px 10px 20px;
}
.checkdiv{
    border: 3px dashed red;
}
div:nth-child(1){
    left: 0px;
    background-color: pink;
}
div:nth-child(2){
    left: 110px;
    background-color: #5ac;
}
div:nth-child(3){
    left: 220px;
    background-color: #fa5;
}
div:nth-child(4){
    left: 330px;
    background-color: #1c5;
}

input[type='button']{
    border: none;
    width: 100px;
    height: 40px;
    color: #c994bd;
    font-weight: 400;
    font-size: 18px;
    position: absolute;
    left: 50px;
    bottom: 50px;
    border: 1px solid #5ac;
}
input[type='button']:hover{
    border: 1px solid #c994bd;
    background-color: rgb(143, 224, 173);
    color: white;
}