首页 > 解决方案 > 在 Chrome 和 Edge 中使用 Javascript 更改 iFrame 大小闪烁

问题描述

我正在使用本机库动态更改 iframe 大小ResizeObserverPostMessage但每次 iframe在ChromeEdgewidth中更改大小(和height)时,它都会闪烁。这真的很奇怪,因为在FirefoxSafari中它按预期工作。

这是我的代码

// Child window
const resize = new ResizeObserver(entries => {
  window.parent.postMessage({ updateIframeSize: { width, height } }, *);
});

resize.observe(document.body);

// Main window
window.addEventListener('message', function (message) {
  const iframeSizeEvt = message.data.updateIframeSize;
    
  if (iframeSizeEvt) {
    const iframeTag = document.getElementById('myIframe');
    
    iframeTag.style.width = `${iframeSizeEvt.width}px`;
    iframeTag.style.height = `${iframeSizeEvt.height}px`;
  }
});

// Iframe
<iframe id="myIframe" src="MY_IFRAME_URL" style="position: fixed; right: 0; bottom: 0; width: 100px; max-width: 100%; height: 100px; max-height: 100%; border: 0; background-color: transparent; opacity: 1; overflow: hidden; z-index: 1000000; box-sizing: border-box;"></iframe>

我还测试了transform: translate3d(0, 0, 0)在 iframe 上添加但没有成功。
有人知道如何解决这种奇怪的眨眼行为吗?

标签: javascriptiframepostmessageiframe-resizer

解决方案


推荐阅读