javascript - 使用 appendChild 将 iframe 移动到其他父级时如何防止 iframe 重新加载

标签 javascript html iframe

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

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

我创建了一个实例来说明这一点。 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>

JavaScript

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

最佳答案

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

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

关于javascript - 使用 appendChild 将 iframe 移动到其他父级时如何防止 iframe 重新加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48930712/

相关文章:

javascript - pouchdb _id 属性值必须是全局唯一的吗?

javascript - 为什么要使用 redux-thunk?

javascript - 显示一个 sessionStorage 项

javascript 在浏览器完成页面渲染之前执行

javascript - 未捕获的类型错误 : Cannot read property 'style' of null at frame

javascript - 在所有其他脚本之后加载 javascript

iframe - 谷歌分析在 iframe 中跟踪不同的合作伙伴

jquery - 从 iFrame 更改父窗口 URL

javascript - 我如何搜索整个数组以找到它的键?

javascript - WordPress - fatal error : "Call to a member function get_var() on a non-object" but only if not as Template