SOURCE

console 命令行工具 X clear

                    
>
console
function dragInit(box, id) {
    var $box = document.getElementById(box);
    var $div = document.getElementById(id);
    var style = {
        position: "absolute",
        top: "0",
        left: "0"
    }
    for (var k in style) {
        $div.style[k] = style[k];
    }
    $div.onmousedown = function(e) { //鼠标按下位置;
        e = e || window.event;
        var x = e.clientX - $div.offsetLeft;
        var y = e.clientY - $div.offsetTop;
        document.onmousemove = function(e) { //鼠标按下后移动位置;
            e = e || window.event;
            var L = e.clientX - x;
            var T = e.clientY - y;
            //var pW = document.documentElement.clientWidth;//页面宽度;
            //var pH = document.documentElement.clientHeight;
            var boxW = $box.offsetWidth;
            var boxH = $box.offsetHeight;
            var divW = $div.offsetWidth; //div的宽;
            var divH = $div.offsetHeight;
            //范围限制
            if (L < 0) {
                L = 0;
            }
            if (T < 0) {
                T = 0;
            }
            //if(L > pW - divW){L = pW - divW;}
            //if(T > pH - divH){T = pH - divH;}
            if (L > boxW - divW) {
                L = boxW - divW;
            }
            if (T > boxH - divH) {
                T = boxH - divH;
            }
            $div.style.left = L + "px";
            $div.style.top = T + "px";
            console.log(L, T);
            //				return {left:L,top:T};

        }
        document.onmouseup = function(e) {
            document.onmousemove = null; //如果不取消,鼠标弹起div依旧会随着鼠标移动
            document.onmouseup = null;

        }

    }
    return $div;
};
window.onload = function (){
   dragInit('parent','children')
}
    
    
<div id="parent">
    <div id="children"></div>
</div>
* {
    margin: 0;
    padding: 0;
}

html,
body {
    height: 100%;
}

#parent {
    position: relative;
    width: 700px;
    height: 470px;
    background: gray;
}

#children {
    position: absolute;
    width: 100px;
    height: 100px;
    background-color: antiquewhite;
    cursor: move;
}