将父窗口的 css 变量应用到 iframe

Ben*_* Li 6 html javascript css iframe

我有一个父窗口和一个 iframe。

在父窗口中html,我有一个 CSS 变量列表:

:root {
  --lp-font-size-heading-lg: 2.5rem;
  --lp-font-size-heading-md: 2rem;
  --lp-font-size-heading-sm: 1.5rem;
}    
Run Code Online (Sandbox Code Playgroud)

但这些变量在 iframe 中不可用,即在 iframe 的标头中,我有:

font-size: var(--lp-font-size-heading-md);
Run Code Online (Sandbox Code Playgroud)

但 iframe 找不到的定义--lp-font-size-heading-md

如何在iframe中添加CSS变量?

小智 0

您可以做的就是在 iFrame 可用时将外部 iFrame 中的变量一一复制到内部 iFrame 中:

    const iframeDocumentElement = document.getElementById('iframeId').contentWindow.document.documentElement;
    const fontLarge = document.documentElement.getPropertyValue('--lp-font-size-heading-lg');
    const fontMedium = document.documentElement.getPropertyValue('--lp-font-size-heading-md');
    iframeDocumentElement.style.setProperty('--lp-font-size-heading-lg', fontLarge);
    iframeDocumentElement.style.setProperty('--lp-font-size-heading-md', fontMedium);
    
Run Code Online (Sandbox Code Playgroud)