JavaScript-拖拽

window.onload = function(){
    var box1= document.getElementById("box1"); //获取元素
    box1.onmousedown = function(event){
        //alert(1);

        //求偏移量
        var offx= event.clientX- box1.offsetLeft;
        var offy= event.clientY -box1.offsetTop;

        document.onmousemove= function(e){
            e= e ||window.e; //解决兼容性

            var x = e.clientX- offx;  //计算位置
            var y = e.clientY -offy ;
            console.log(x);
            box1.style.left = x   +"px";
            box1.style.top = y + "px";

        }
        document.onmouseup = function(){
            document.onmousemove= null;
            document.onmouseup= null; //停止该函数? 我用return 0也能停止呀 
            //alert(1);
        };
    };
原文地址:https://www.cnblogs.com/lwthhh/p/12875325.html