首页 > 解决方案 > 将 dom 元素推入 window.open() 会破坏原始页面

问题描述

jsFiddle

运行以下代码时,我希望它在新窗口中打开内容。

它按预期工作,但会产生一个问题,即它会破坏来自原始页面的推送内容。

<script>
  function myFunction() {
    const html = event.target.parentNode.parentNode.parentNode.parentNode.lastChild;
    const win = window.open(
      '',
      '_blank',
      'toolbar=no,location=no,directories=no,status=no,menubar=no,scrollbars=yes,resizable=yes,width=780,height=200,top=' + (screen.height - 400) + ',left=' + (screen.width - 840));
    win.document.body.style.margin = '0px';
    win.document.body.appendChild(html);
  }
</script>

<div onclick="myFunction()">
  <div>
    <h1>Hello</h1>
    <p>This is just a sample to show what is happening</p>
  </div>
</div>

请参阅jsFiddle上的示例,因为我无法在此处使用脚本。

为什么代码会从页面中删除内容?

在 vanilla JS 中是否有更好的方法来解决这个问题?

任何帮助将不胜感激。

标签: javascripthtmldom

解决方案


在追加之前克隆元素

win.document.body.appendChild(html.cloneNode());

推荐阅读