覆盖iframe中内容的正文样式

时间:2011-06-27 14:49:30

标签: css iframe styles override

如何在iframe内控制身体元素的背景图像和颜色?请注意,嵌入的body元素有一个类,iframe是我网站的一部分页面。

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

iframe的主体在编辑器中有一个其他地方没有使用过的类,所以我假设这个被放在那里,所以这样的问题可以解决。但是,当我将样式应用于class.body时,它们不会覆盖应用于body的样式。奇怪的是,样式确实出现在Firebug中,所以我不知道发生了什么!

谢谢

更新 - 我已经尝试过@mikeq的解决方案,即将类型添加到正文类的类中。这在添加到主页的样式表时不起作用,但在使用Firebug添加时它确实有效。我假设这是因为Firebug应用于页面上的所有元素,而CSS不应用于iframe中。这是否意味着在使用JavaScript加载窗口后添加css会起作用?

11 个答案:

答案 0 :(得分:232)

以下内容仅适用于iframe内容来自同一父域的情况。

以下jquery脚本适合我。在Chrome和IE8上测试过。内部iframe引用与父页面位于同一域的页面。

在这种特殊情况下,我在内部iframe中隐藏了一个具有特定类的元素。

基本上,您只需将'style'元素附加到内部iframe的“head”。

$('iframe').load( function() {
    $('iframe').contents().find("head")
      .append($("<style type='text/css'>  .my-class{display:none;}  </style>"));
});

答案 1 :(得分:96)

iframe是页面中的“洞”,显示其中的另一个网页。 iframe的内容不是任何形状,也不是父页面的一部分。

正如其他人所说,你的选择是:

  • 为iframe中加载的文件提供必要的CSS
  • 如果iframe中的文件来自与您父级相同的域,则可以从父级访问iframe中的文档的DOM。

答案 2 :(得分:25)

除非您具有直接访问权限,因此您无法更改iframe中显示的网页的样式,因此您拥有源html和/或css文件的所有权。

这是为了停止XSS (Cross Site Scripting)

答案 3 :(得分:7)

iframe有另一个范围,因此您无法使用javascript访问它或使用javascript更改其内容。

它基本上是“另一页”。

你唯一能做的就是编辑自己的CSS,因为使用全局CSS你无法做任何事情。

答案 4 :(得分:5)

覆盖其他域 iframe CSS

通过使用SimpleSam5's answer的一部分,我通过一些Tawk的聊天iframe实现了这一点(他们的customization interface很好,但我还需要进一步的自定义。)

在移动设备上显示的这个特定iframe中,我需要隐藏默认图标并放置我的一个背景图片。我做了以下事情:

Tawk_API.onLoad = function() {
// without a specific API, you may try a similar load function
// perhaps with a setTimeout to ensure the iframe's content is fully loaded
  $('#mtawkchat-minified-iframe-element').
    contents().find("head").append(
     $("<style type='text/css'>"+
       "#tawkchat-status-text-container {"+
         "background: url(https://example.net/img/my_mobile_bg.png) no-repeat center center blue;"+
         "background-size: 100%;"+
       "} "+
       "#tawkchat-status-icon {display:none} </style>")
   );
};

我没有任何Tawk的域名,这对我有用,因此你可以这样做,即使它不是来自同一个父域(尽管Sam的回答是Jeremy Becker's comment)。

答案 5 :(得分:2)

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

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);

答案 6 :(得分:1)

如果您可以控制托管iframe的页面和iframe的页面,则可以将查询参数传递给iframe ...

以下是根据托管网站是否移动来向iframe添加类的示例...

添加iFrame:

var isMobile=$("mobile").length; //detect if page is mobile
var iFrameUrl ="https://myiframesite/?isMobile=" + isMobile; 

$(body).append("<div id='wrapper'><iframe src=''></iframe></div>");
$("#wrapper iframe").attr("src", iFrameUrl ); 

内部iFrame:

//add mobile class if needed
var url = new URL(window.location.href);
var isMobile = url.searchParams.get("isMobile");
if(isMobile == "1") {
    $("body").addClass("mobile");
}

答案 7 :(得分:0)

我有一个blog,并且在寻找如何调整嵌入式gist大小时遇到​​很多麻烦。邮政管理器仅允许您编写文本,放置图像和嵌入HTML代码。博客布局本身就是响应式的。它是用Wix构建的。但是,嵌入式HTML并非如此。我读了很多关于如何调整生成的iFrame主体内部组件大小的知识。所以,这是我的建议:

如果iFrame中只有一个组件(即要点),则只能调整要点的大小。忘了iFrame。

我在视口,针对不同用户代理的特定布局方面遇到了问题,这就是解决我问题的方法:

<script language="javascript" type="text/javascript" src="https://gist.github.com/roliveiravictor/447f994a82238247f83919e75e391c6f.js"></script>

<script language="javascript" type="text/javascript">

function windowSize() {
  let gist = document.querySelector('#gist92442763');

  let isMobile = {
    Android: function() {
        return /Android/i.test(navigator.userAgent)
    },
    BlackBerry: function() {
        return /BlackBerry/i.test(navigator.userAgent)
    },
    iOS: function() {
        return /iPhone|iPod/i.test(navigator.userAgent)
    },
    Opera: function() {
        return /Opera Mini/i.test(navigator.userAgent)
    },
    Windows: function() {
        return /IEMobile/i.test(navigator.userAgent) || /WPDesktop/i.test(navigator.userAgent)
    },
    any: function() {
        return (isMobile.Android() || isMobile.BlackBerry() || isMobile.iOS() || isMobile.Opera() || isMobile.Windows());
    }
};

  if(isMobile.any()) {
    gist.style.width = "36%";
    gist.style.WebkitOverflowScrolling = "touch"
    gist.style.position = "absolute"
  } else {
    gist.style.width = "auto !important";
  }
}

windowSize();

window.addEventListener('onresize', function() {
    windowSize();
});

</script>

<style type="text/css">

.gist-data {
  max-height: 300px;
}

.gist-meta {
  display: none;
}

</style>

逻辑是根据用户代理设置要点(或您的组件)css。在应用到查询选择器之前,请确保先标识您的组件。 Feel free to take a look how responsiveness is working

希望能帮助别人;)

欢呼

答案 8 :(得分:0)

如果您是两者的所有者,这应该适用于跨域

这里的技巧是为您的正文分配一个全局 css 变量,以新颜色收听消息,然后在收到消息后更改全局 css 变量。

我使用的是 angular,但它应该适用于纯 javascript

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

域 A

@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);
}

答案 9 :(得分:-4)

现在可能已经改变了,但我使用了一个单独的样式表来填充这个元素:

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

成功设置嵌入式youtube iframe样式...请参阅the blog posts on this page

答案 10 :(得分:-23)

为您的iframe页面的正文提供ID(或者如果您愿意的话)

<html>
<head></head>
<body id="myId">
</body>
</html>

然后,也在iframe的页面中,为CSS中的背景分配背景

#myId {
    background-color: white;
}
相关问题