簡體   English   中英

拖放div奇怪的行為

[英]Drag and Drop div weird behavior

我正在嘗試制作一個可以動態添加更多divs或刪除一些div的多個div拖放。

第一次它工作得很好,但如果我嘗試再次運行該函數,它的行為會很奇怪。

  • 它通過在任何位置拖動來移動,而不僅僅是像以前一樣在標題中。
  • 所有動作都轉到最后一個 div。
  • 不能再在 textarea 中寫了。

 var applyDrag = () => { Array.prototype.slice.call(document.querySelectorAll(".contentCon")).forEach(e=>{ e.querySelector("h1").onmousedown = null; dragElement(e); console.log(e.querySelector("h1").innerText); }); } applyDrag(); var moveRoom = document.querySelector(".mainCon"); function dragElement(elmnt) { elmnt.style.background = "blue"; var dragEl = elmnt.querySelector("h1"); dragEl.style.cursor = "move"; console.log(dragEl.innerText); var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (moveRoom) { moveRoom.onmousedown = dragMouseDown; } else { dragEl.onmousedown = dragMouseDown; } function dragMouseDown(e) { console.log(dragEl); e = e || window.event; e.preventDefault(); pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; document.onmousemove = elementDrag; } function elementDrag(e) { e = e || window.event; 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() { document.onmouseup = null; document.onmousemove = null; } }
 <body> <div class="mainCon"> <div class="contentCon" id="mainCode" style="position: absolute;"> <h1>Main block</h1> <button onclick="applyDrag()">Submit</button> <br> <textarea cols="10" rows="10" spellcheck="false">Click the "Submit" button to run the Drag and Drop function again. Internal code not applied.</textarea> </div> <div class="contentCon" style="position: absolute;"> <h1>Exit log</h1> <br> <textarea id="ExitLog" cols="10" rows="10" spellcheck="false" readonly style="cursor: auto; width: 300;">Internal code not applied.</textarea> </div> </div> </body>

請在 dragElement 函數中替換這些行。

if (moveRoom) {
    moveRoom.onmousedown = dragMouseDown;
}
else {
    dragEl.onmousedown = dragMouseDown;
}

就去做吧

dragEl.onmousedown = dragMouseDown;

它在第一次運行時工作,因為第一次調用 moveRoom 時為空,當其他部分運行時,onmousedown 函數被正確分配給 dragEl 但在第二次運行時它不為空,並且 onmousedown 函數被分配給 moveRoom 元素。

暫無
暫無

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

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