我需要将 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/