js鼠标拖动元素移动

拖动元素移动

 var odiv = document.getElementsByTagName('div')[0];

    //给需要移动的元素添加onmousedown事件
    odiv.onmousedown = function (ev) {
        var event = window.event || ev;
        // 获取屏幕中可视化的宽高的坐标
        var dx = event.clientX - odiv.offsetLeft; 
        var dy = event.clientY - odiv.offsetTop;
      console.log(event);
      console.log(dy)
        //实时改变目标元素odiv的位置
        document.onmousemove = function (ev) {
            var event = window.event || ev;
            odiv.style.left = event.clientX - dx + 'px';
            odiv.style.top = event.clientY - dy + 'px';
        }

        //抬起停止拖动
        document.onmouseup = function () {
            document.onmousemove = null;
            document.onmouseup = null;

        }
    }
    

效果图
js鼠标拖动元素移动_第1张图片

你可能感兴趣的:(js鼠标拖动元素移动)