如何控制iframe中主体元素的背景图像和颜色?注意,嵌入的body元素有一个类,iframe是属于我的站点的一个页面。

我需要这个的原因是,我的网站有一个黑色背景分配给主体,然后一个白色背景分配给包含文本的div。所见即所得编辑器在编辑时使用iframe来嵌入内容,但它不包括div,因此文本很难阅读。

iframe的主体在编辑器中有一个在其他任何地方都不使用的类,所以我假设这个放在那里是为了解决这样的问题。然而,当我将样式应用到类时。它们不会覆盖应用于Body的样式。奇怪的是,样式确实出现在Firebug中,所以我不知道发生了什么!

谢谢

更新-我已经尝试了@mikeq的解决方案,添加一个样式的类,是身体的类。这在添加到主页的样式表时不起作用,但在添加到Firebug时起作用。我假设这是因为Firebug应用于页面上的所有元素,而CSS没有应用于iframes中。这是否意味着添加css后窗口加载与JavaScript将工作?


当前回答

也许现在它已经改变了,但我已经使用了一个单独的样式表与这个元素:

.feedEkList iframe
{
max-width: 435px!important;
width: 435px!important;
height: 320px!important;
}

要成功地设计嵌入YouTube iframes…请参阅本页的博客文章。

其他回答

iframe有另一个作用域,所以你不能访问它的样式或用javascript改变它的内容。

基本上就是“另一页”。

你唯一能做的就是编辑它自己的CSS,因为你的全局CSS你什么都做不了。

对于一个iframe,你可以这样做:

document.querySelector('iframe').contentDocument.body.style.backgroundColor = '#1e1e2d';

如果你有多个iframe,你正在处理:

document.querySelectorAll('iframe').forEach((iframe) => {
    iframe.contentDocument.body.style.backgroundColor = '#1e1e2d';
});

这段代码使用了普通JavaScript。它创建了一个新的<style>元素。它将该元素的文本内容设置为包含新CSS的字符串。它将该元素直接追加到iframe文档的头部。

但是请记住,访问从其他来源加载的文档的元素是不允许的(出于安全原因)——当从嵌入框架的页面的浏览上下文尝试时,iframe元素的contentDocument将计算为null。

var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
  'body {' +
  '  background-color: some-color;' +
  '  background-image: some-image;' +
  '}' 
;
iframe.contentDocument.head.appendChild(style);

这应该与跨域工作,如果你是两者的所有者

这里的技巧是为你的主体分配一个全局css变量,用新颜色监听消息,然后在收到消息后更改全局css变量。

我使用角,但它应该与纯javascript工作

我的用例是在保存之前向用户展示颜色变化如何影响他在iframe中的网站

域一个

@ViewChildren('iframeContainer') iframeContainer: QueryList<ElementRef>

sendDataToIframe(
  data = {
      type: 'colorChange',
      colors: {primary: '#000', secondary: '#fff'},
  },
): void {
  if (this.targetUrl)
    this.iframeContainer.first.nativeElement.contentWindow.postMessage(data) // You may use document.getElementById('iframeContainer') instead
}

域B

acceptedEditOrigins = [
  'https://my.origine.ccom', // Be sur to have a correct origin, to avoid xss injecto: https://en.wikipedia.org/wiki/Cross-site_scripting
]

constructor() {
// Listen to message
window.addEventListener('message', (event) => this.receiveMessage(event), false)
}

receiveMessage(event: MessageEvent) {
  if (this.acceptedEditOrigins.includes(event.origin))
    switch (event.data.type) {
      case 'colorChange': {
        this.setWebsiteConfigColor(event.data.colors)
      }
    }
}

setWebsiteConfigColor(colors: WebsiteConfigColors) {
  if (colors) {
    const root = document.documentElement
    for (const [key, value] of Object.entries(colors)) {
       root.style.setProperty(`--${key}`, value) // --primary: #000, --secondary: #fff
    }
  }
}

body {
  background-color: var(--primary);
}

您不能更改iframe中显示的页面的样式,除非您可以直接访问并拥有源html和/或css文件。

这是为了停止XSS(跨站点脚本)