我有一个简单的页面,有一些iframe部分(显示RSS链接)。如何将相同的CSS格式从主页应用到iframe中显示的页面?
当前回答
如果你有访问iframe页面,想要一个不同的CSS应用在它上,只有当你加载它通过iframe在你的页面上,在这里我找到了一个解决方案,这类事情
即使iframe正在加载不同的域,这也是有效的
检查postMessage()
计划是,将CSS作为消息发送到iframe
iframenode.postMessage('h2{color:red;}','*');
*是发送这条消息,不管它在iframe中的哪个域
并在iframe中接收消息,并将接收到的消息(CSS)添加到该文档头。
在iframe页面中添加的代码
window.addEventListener('message',function(e){
if(e.data == 'send_user_details')
document.head.appendChild('<style>'+e.data+'</style>');
});
其他回答
你不能这样样式iframe的内容。我的建议是使用服务器端脚本(PHP、ASP或Perl脚本),或者找到可以将提要转换为JavaScript代码的在线服务。唯一的另一种方法是如果你能做一个服务器端包含。
下面的方法对我很有效。
var iframe = top.frames[name].document;
var css = '' +
'<style type="text/css">' +
'body{margin:0;padding:0;background:transparent}' +
'</style>';
iframe.open();
iframe.write(css);
iframe.close();
编辑:除非设置了适当的CORS报头,否则不能跨域工作。
这里有两个不同的东西:iframe块的样式和嵌入在iframe中的页面的样式。你可以用通常的方法设置iframe块的样式:
<iframe name="iframe1" id="iframe1" src="empty.htm"
frameborder="0" border="0" cellspacing="0"
style="border-style: none;width: 100%; height: 120px;"></iframe>
iframe中嵌入的页面样式必须通过在子页面中包含它来设置:
<link type="text/css" rel="Stylesheet" href="Style/simple.css" />
或者它可以从父页面加载Javascript:
var cssLink = document.createElement("link");
cssLink.href = "style.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
frames['iframe1'].document.head.appendChild(cssLink);
扩展上面的jQuery解决方案来处理加载帧内容的延迟。
$('iframe').each(function(){
function injectCSS(){
$iframe.contents().find('head').append(
$('<link/>', { rel: 'stylesheet', href: 'iframe.css', type: 'text/css' })
);
}
var $iframe = $(this);
$iframe.on('load', injectCSS);
injectCSS();
});
如果你有访问iframe页面,想要一个不同的CSS应用在它上,只有当你加载它通过iframe在你的页面上,在这里我找到了一个解决方案,这类事情
即使iframe正在加载不同的域,这也是有效的
检查postMessage()
计划是,将CSS作为消息发送到iframe
iframenode.postMessage('h2{color:red;}','*');
*是发送这条消息,不管它在iframe中的哪个域
并在iframe中接收消息,并将接收到的消息(CSS)添加到该文档头。
在iframe页面中添加的代码
window.addEventListener('message',function(e){
if(e.data == 'send_user_details')
document.head.appendChild('<style>'+e.data+'</style>');
});
推荐文章
- 使伸缩项目正确浮动
- 如何取消最大高度?
- 形式内联内的形式水平在twitter bootstrap?
- 自定义元素在HTML5中有效吗?
- 如何选择在最后一个子元素之前的元素?
- 如何触发自动填充在谷歌Chrome?
- CSS变换,锯齿边缘在铬
- 创建圈div比使用图像更容易的方法?
- 强迫孩子服从父母的弯曲边界在CSS
- 为什么Chrome浏览器不正确地确定页面是在不同的语言,并提供翻译?
- 在CSS中@apply是什么?
- 在网页上用鼠标模拟震颤(例如帕金森病)?
- Bootstrap抛出Uncaught错误:Bootstrap的JavaScript需要jQuery
- 如何改变文本区域的边框颜色:焦点
- 我如何设置背景颜色为文本的宽度,而不是整个元素的宽度,使用CSS?