【问题标题】:how to make multiple movable elements如何制作多个可移动元素
【发布时间】:2020-03-20 18:25:00
【问题描述】:

我有这个用于创建可移动窗口(元素)的代码,我在创建新窗口时调用了这个函数:

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;
    }
}

问题是:

如果我创建一个新窗口,我不能移动他们之前创建的窗口。

【问题讨论】:

  • 你应该在用户点击窗口时调用这个函数
  • @MARSHMALLOW 这给了我真正的答案!非常感谢!

标签: javascript html window movable


【解决方案1】:

当您向上移动鼠标时,函数 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;
    }
}

参考:https://stackoverflow.com/a/322827/8031896

【讨论】:

  • 哦,这是另一个问题,在 mouseup 窗口仍然随着鼠标移动而移动之后。
  • @A.L.哦,没想到会这样。编辑后的版本引入了一个额外的变量来记录鼠标按下状态。希望这会奏效。
【解决方案2】:

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

所以,当我创建一个新窗口时,我应该为每个窗口再次调用dragWindow。

【讨论】:

    猜你喜欢
    • 2021-12-18
    • 2012-04-22
    • 2011-05-10
    • 1970-01-01
    • 2021-07-05
    • 2023-01-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多