如何使用按钮在JS中删除<div>

时间:2019-12-19 17:48:43

标签: javascript html css

这是我的代码:

//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,最终它最终会自我破坏。我读了许多其他文章,但没有一篇对我有用。任何帮助,将不胜感激。谢谢!

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您可以通过Element.remove()

使用JavaScript从DOM中删除元素和元素

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

在您的情况下,您需要先引用元素mydiv,然后再单击.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>