簡體   English   中英

如何刪除一個<div>在 JS 中使用按鈕

[英]How to delete a <div> in JS using a button

這是我的代碼:

 //Make the DIV element draggagle: dragElement(document.getElementById("mydiv")); function dragElement(elmnt) { var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0; if (document.getElementById(elmnt.id + "header")) { /* if present, the header is where you move the DIV from:*/ document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown; } else { /* otherwise, move the DIV from anywhere inside the DIV:*/ elmnt.onmousedown = dragMouseDown; } function dragMouseDown(e) { e = e || window.event; e.preventDefault(); // get the mouse cursor position at startup: pos3 = e.clientX; pos4 = e.clientY; document.onmouseup = closeDragElement; // call a function whenever the cursor moves: document.onmousemove = elementDrag; } function elementDrag(e) { e = e || window.event; e.preventDefault(); // calculate the new cursor position: pos1 = pos3 - e.clientX; pos2 = pos4 - e.clientY; pos3 = e.clientX; pos4 = e.clientY; // set the element's new position: elmnt.style.top = (elmnt.offsetTop - pos2) + "px"; elmnt.style.left = (elmnt.offsetLeft - pos1) + "px"; } function closeDragElement() { /* stop moving when mouse button is released:*/ document.onmouseup = null; document.onmousemove = null; } }
 <div id="mydiv"> <div id="mydivheader">LiveChat <a href="#RESETlivechat&ERR_4F0" class="close-div">Close</a></div> <iframe class="live" src="https://tlk.io/friv432" width="400" height="400">TROUBLE LOADING LIVECHAT... ERR_4F0</iframe> </div>

而且我不想使用#mydivheader 中的關閉按鈕刪除#mydiv,最終它會自行銷毀它。 我閱讀了許多其他文章,但沒有一篇對我有用。 任何幫助,將不勝感激。 謝謝!

 document.getElementById("btn").addEventListener("click", () => { document.getElementById("rmv").remove() })
 <div id="rmv">Remove Me!</div> <button id="btn">Click to remove</button>

您可以通過Element.remove()使用 JavaScript 從 DOM 中刪除和元素

https://developer.mozilla.org/en-US/docs/Web/API/ChildNode/remove

在您的情況下,您需要獲取對元素mydiv的引用,然后在單擊mydivheadermydivheader該節點的.remove() mydivheader

例子:

 const divHeader = document.getElementById('mydivheader'); divHeader.addEventListener('click', e => { const div = document.getElementById('mydiv'); if (div) { div.remove(); } });
 <div id="mydiv"> <div id="mydivheader">LiveChat <a href="#RESETlivechat&ERR_4F0" class="close-div">Close</a></div> <iframe class="live" src="https://tlk.io/friv432" width="400" height="400">TROUBLE LOADING LIVECHAT... ERR_4F0</iframe> </div>

暫無
暫無

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

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