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);
        };
    };
posted @ 2020-05-12 12:02  槐序十五  阅读(99)  评论(0编辑  收藏  举报