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');
}
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();
}
}
}
Drag.prototype.toDown = function(ev){
this.disX = ev.clientX - this.obj.offsetLeft;
this.disY = ev.clientY - this.obj.offsetTop;
this.obj.classList.add('checkdiv');
}
Drag.prototype.toMove = function(ev){
this.obj.style.left = ev.clientX - this.disX + 'px';
this.obj.style.top = ev.clientY - this.disY + 'px';
}
Drag.prototype.toUp = function(){
document.onmousedown = null;
document.onmousemove = null;
this.obj.classList.remove('checkdiv')
}
let btn = document.querySelector('input[type="button"]');
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';
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;
}