Js drag effect

Drag and drop: when clicking on a div, hold down the mouse pointer, move the mouse pointer, and the div will move as well. As long as you get the distance of the mouse pointer relative to the current div, the div will move to the new position, and the relative distance will not change.

var node1 = document.getElementById("div1");// Get the node
drag(node1);// Call the method
function drag(node){
    //1. Add mouseDown and record the relative distance
    node.onmousedown = function(ev){
        var e = ev || window.event;// Compatible with event objects
        var offsetX = e.clientX - node.offsetLeft;// Mouse click the distance relative to the current div
        var offsetY = e.clientY - node.offsetTop;

        // mousemove, keep a relative distance to follow the mouse
        document.onmousemove = function(ev){
            var e = ev || window.event;

            node.style.left = e.clientX - offsetX + 'px';// The mouse position minus the relative distance is the new position
            node.style.top = e.clientY - offsetY + 'px'; }}//3, cancel drag
    document.onmouseup = function(){
        document.onmousemove = null;// Cancel the move event}}Copy the code