如何制作多个可移动元素

how to make multiple movable elements

我有创建可移动 windows(元素)的代码,我在创建新的 window 时调用此函数:

function dragWindow(elmnt) {
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    elmnt.querySelector(".window-caption").onmousedown = dragMouseDown;
    function dragMouseDown(e) {
        e.preventDefault();
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
    }
    function elementDrag(e) {
        e.preventDefault();
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    }
    function closeDragElement() {
        // alert(elmnt.id);
        document.onmouseup = null;
        document.onmousemove = null;
    }
}

问题是:

if I create a new window, I can't move windows they created before.

当您向上移动鼠标时,函数 closeDragElement() 被调用并且事件侦听器 document.onmousemove 被覆盖为 'null'。

注释掉函数closeDragElement()中的最后一行可能会解决这个问题:

function closeDragElement() {
        // alert(elmnt.id);
        document.onmouseup = null;
        // document.onmousemove = null;
}

编辑:添加了一个变量 mousedown 来指示鼠标是否按下。

function dragWindow(elmnt) {
    var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
    var mousedown = 0;
    elmnt.querySelector(".window-caption").onmousedown = dragMouseDown;
    function dragMouseDown(e) {
        e.preventDefault();
        mousedown++;
        pos3 = e.clientX;
        pos4 = e.clientY;
        document.onmouseup = closeDragElement;
        document.onmousemove = elementDrag;
    }
    function elementDrag(e) {
        e.preventDefault();
        if (mousedown === 0) {return;}
        pos1 = pos3 - e.clientX;
        pos2 = pos4 - e.clientY;
        pos3 = e.clientX;
        pos4 = e.clientY;
        elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
        elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
    }
    function closeDragElement() {
        // alert(elmnt.id);
        mousedown--;
        document.onmouseup = null;
        //document.onmousemove = null;
    }
}

参考:

我在每个 windows 上再次调用了该函数(在开发者控制台中);它向我展示了正确的答案:

So, when I create a new window, I should call dragWindow again for each window.