簡體   English   中英

如何制作多個可移動元素

[英]how to make multiple movable elements

我有這個用於創建可移動窗口(元素)的代碼,我在創建新窗口時調用這個函數:

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

問題是:

如果我創建一個新窗口,我不能移動他們之前創建的窗口。

當您向上移動鼠標時,函數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

我在每個窗口上再次調用了該函數(在開發者控制台中); 它向我展示了正確的答案:

因此,當我創建一個新窗口時,我應該為每個窗口再次調用 dragWindow。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM