JSFiddle - React, Tailwind, and code Playground
by dont27
HTML
<div id="app">
<div class="drag"></div>
</div>
CSS
#app{
width: 800px;
margin:50px auto;
position: relative;
}
.drag{
position: absolute;
top: 20px;
left: 30px;
cursor: crosshair;
border: 1px solid #000;
padding: 5px;
width:20px;
height:20px;
background-color:red;
}
JavaScript
(function(){
function getStyle(elem){
return getComputedStyle(elem);
}
function parsePx(str){
if(/px/.test(str)){
str = str.replace(/px/,'');
}
return parseFloat(str);
}
var drag = document.querySelector('.drag');
var top,
left,
currentX,
currentY,
moving = false;
drag.onmousedown = function(event){
var css = getStyle(drag);
top = parsePx(css.top);
left = parsePx(css.left);
//console.log('down',top,left);
currentX = event.clientX;
currentY = event.clientY;
moving = true
};
document.onmouseup = function(event){
//console.log('up');
moving = false;
currentX = currentY = top = left =0;
};
drag.onmousemove = function(event){
if(!moving)return;
drag.style.top = top + (event.clientY - currentY) + 'px';
drag.style.left = left + (event.clientX - currentX) + 'px';
};
drag.onmouseleave = function(event){
moving = false;
currentX = currentY = top = left =0;
};
})()