JSFiddle - React, Tailwind, and code Playground

by wang lei

HTML

<div id="box">
    <div id="children" style="position:absolute;left: 100px;top: 100px; width: 50px;height: 50px;background: red;"></div>
</div>

CSS

#box {
  width: 1000px;
  height: 600px;
  background: #ccc;
  
  /* margin: 50px 0 0 100px; */
}

JavaScript

var qwe = document.getElementById('box');
    var rec = document.getElementById("children")
    var down = false;
    var dx = 0; // 获取鼠标按下的盒子某个位置的相对浏览器可视区域坐标
    var sx = 0; // 获取原始
    qwe.onmousemove = function(e){
        if (down) {
            var ev = e || event;
           /*  文档区域 - 距离父元素 */
            rec.style.left = ev.clientX - (dx - sx) + 'px';
        }
    }
    rec.onmousedown = function(){
        dx = event.clientX; // 获取距离文档区域的
        sx = parseInt(rec.style.left); // 元素距离父元素的left
        if (!down) {
            down  = true;
        }
    }
    qwe.onmouseup = function(){
        if (down) {
            down = false;
        }
    }