使用appendChild将iframe移动到不同的父级时如何防止iframe重新加载

nes*_*est 5 html javascript iframe

我需要将 iframe 移动到不同的父元素,保持 iframe 状态(保留滚动位置和可能已输入表单的任何信息等)

当使用 iframe 元素移动时,appendChild()它也会重新加载,从而重置状态。有可能阻止这种情况吗?

我创建了一个实例来说明这一点。https://jsbin.com/kejoweniva/edit?output

打开示例,滚动然后单击按钮,当附加到新的父级时,iframe 会自动重新加载。

html

  <div class="target"></div>
  <iframe src="https://2017.cssconf.eu/"></iframe>
  <button onclick="moveIframe()">move iframe</button>
Run Code Online (Sandbox Code Playgroud)

javascript

function moveIframe() {
  console.log('moving iframe')
  var iframe = document.getElementsByTagName('iframe')[0]
  document.getElementsByClassName('target')[0].appendChild(iframe)
}
Run Code Online (Sandbox Code Playgroud)

小智 4

在不重新加载的情况下,不可能将 iframe 从 dom 中的一个位置移动到另一个位置。appendChild()当您尝试使用或 等方法移动 iframe 时,浏览器如何解释事件是一个错误insertBefore()

如果您只需要移动页面上的 IFrame,则可以使用 css 解决方法。这是一个基于您的工作的JsFiddle 示例。