我有一个简单的页面,其中有一些iframe部分(用于显示RSS链接)。我怎样才能将主页面的CSS格式应用到iframe中显示的页面上?
_Edit:___除非设置了适当的[CORS头][1],否则这在跨域中是行不通的。
这里有两个不同的东西。 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);
[1]: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS
我在谷歌日历上遇到了这个问题。 我想把它改成深色背景的样式,并改变字体。
幸运的是,嵌入代码中的URL没有直接访问的限制,所以通过使用PHP函数file_get_contents
,可以得到以下内容
整个页面的内容。
不调用谷歌的URL,可以调用一个位于你服务器上的php文件,如
google.php
,它将包含原始内容和修改。
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
将路径添加到你的样式表中。
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
(这将会把你的样式表放在最后,就在head
结束标签之前。)
在原始url的基础上指定url,以防止css和js被相对调用。
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
最后的 "google.php "文件应该是这样的。
<?php
$content = file_get_contents('https://www.google.com/calendar/embed?src=%23contacts%40group.v.calendar.google.com&ctz=America/Montreal');
$content = str_replace('</title>','</title><base href="https://www.google.com/calendar/" />', $content);
$content = str_replace('</head>','<link rel="stylesheet" href="http://www.yourwebsiteurl.com/google.css" /></head>', $content);
echo $content;
然后你把iframe
嵌入代码改成。
<iframe src="http://www.yourwebsiteurl.com/google.php" style="border: 0" width="800" height="600" frameborder="0" scrolling="no"></iframe>
运气好
如果iframe的内容不完全在你的控制之下,或者你想从不同的页面访问不同风格的内容,你可以尝试用JavaScript来操作它。
var frm = frames['frame'].document;
var otherhead = frm.getElementsByTagName("head")[0];
var link = frm.createElement("link");
link.setAttribute("rel", "stylesheet");
link.setAttribute("type", "text/css");
link.setAttribute("href", "style.css");
otherhead.appendChild(link);
请注意,根据你使用的浏览器,这可能只对来自同一域名的页面起作用。
var $head = $("#eFormIFrame").contents().find("head");
$head.append($("<link/>", {
rel: "stylesheet",
href: url,
type: "text/css"
}));
以上稍加改动就可以了。
var cssLink = document.createElement("link")
cssLink.href = "pFstylesEditor.css";
cssLink.rel = "stylesheet";
cssLink.type = "text/css";
//Instead of this
//frames['frame1'].document.body.appendChild(cssLink);
//Do this
var doc=document.getElementById("edit").contentWindow.document;
//If you are doing any dynamic writing do that first
doc.open();
doc.write(myData);
doc.close();
//Then append child
doc.body.appendChild(cssLink);
至少在ff3和ie8下可以正常工作。
如果你想重用主页面的CSS和JavaScript,也许你应该考虑用Ajax加载的内容替换<IFRAME>
。
现在当搜索机器人能够执行JavaScript时,这对SEO更加友好。
这是jQuery的例子,在你的文档中包含了另一个html页面。
这比iframe
更有利于SEO。
为了确保机器人不会对包含的页面进行索引,只需在robots.txt
中添加它为不允许。
<html>
<header>
<script src="/js/jquery.js" type="text/javascript"></script>
</header>
<body>
<div id='include-from-outside'></div>
<script type='text/javascript'>
$('#include-from-outside').load('http://example.com/included.html');
</script>
</body>
</html>
你也可以直接从Google中加入jQuery。 http://code.google.com/apis/ajaxlibs/documentation/ - 这意味着可以选择自动包含较新的版本和一些显著的速度增加。 同时,也意味着你必须相信他们只提供给你jQuery;)
在上述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();
});
我的紧凑版。
<script type="text/javascript">
$(window).load(function () {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
});
</script>
但是,有时在加载窗口时iframe
还没有准备好,所以需要使用定时器。
即用型代码(带定时器)。
<script type="text/javascript">
var frameListener;
$(window).load(function () {
frameListener = setInterval("frameLoaded()", 50);
});
function frameLoaded() {
var frame = $('iframe').get(0);
if (frame != null) {
var frmHead = $(frame).contents().find('head');
if (frmHead != null) {
clearInterval(frameListener); // stop the listener
frmHead.append($('style, link[rel=stylesheet]').clone()); // clone existing css link
//frmHead.append($("<link/>", { rel: "stylesheet", href: "/styles/style.css", type: "text/css" })); // or create css link yourself
}
}
}
</script>
...和jQuery链接。
<script src="https://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.9.1.min.js" type="text/javascript"></script>
这里的其他答案似乎使用jQuery和CSS链接。
这段代码使用的是vanilla JavaScript,它创建了一个新的<style>
元素。
它创建了一个新的<style>
元素。
它将该元素的文本内容设置为一个包含新CSS的字符串。
并将该元素直接附加到 iframe 文档的头部。
var iframe = document.getElementById('the-iframe');
var style = document.createElement('style');
style.textContent =
'.some-class-name {' +
' some-style-name: some-value;' +
'}'
;
iframe.contentDocument.head.appendChild(style);
当你说"doc.open()" 意味着你可以在iframe里面写任何HTML标签,所以你应该写下所有HTML页面的基本标签,如果你想在你的iframe头部有一个CSS链接,就写一个带有CSS链接的iframe。 我给你举个例子。
doc.open();
doc.write('<!DOCTYPE html><html><head><meta charset="utf-8"/><meta http-quiv="Content-Type" content="text/html; charset=utf-8"/><title>Print Frame</title><link rel="stylesheet" type="text/css" href="/css/print.css"/></head><body><table id="' + gridId + 'Printable' + '" class="print" >' + out + '</table></body></html>');
doc.close();
如果你有访问iframe页面的权限,并且希望只有当你通过iframe加载它时,才可以应用不同的CSS,我在这里找到了一个解决这些事情的方法。
即使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>');
});
我找到了另一个解决方案,把样式放在主html中,就像这样。
<style id="iframestyle">
html {
color: white;
background: black;
}
</style>
<style>
html {
color: initial;
background: initial;
}
iframe {
border: none;
}
</style>
然后在iframe中这样做(见js onload)
<iframe onload="iframe.document.head.appendChild(ifstyle)" name="log" src="/upgrading.log"></iframe>
而在js中
<script>
ifstyle = document.getElementById('iframestyle')
iframe = top.frames["log"];
</script>
它可能不是最好的解决方案,当然也可以改进,但如果你想保留一个"style".标签,它是另一种选择。 标签,那么它就是另一种选择。
在这里,域内有两个东西
在iFrame内加载的页面
所以你要把这两部分的样式如下。
1. iFrame部分的风格
它可以使用CSS的id
或class
名称进行样式设计。
你也可以在你的父级样式表中为它设置样式。
<style>
#my_iFrame{
height: 300px;
width: 100%;
position:absolute;
top:0;
left:0;
border: 1px black solid;
}
</style>
<iframe name='iframe1' id="my_iFrame" src="#" cellspacing="0"></iframe>
2. 在iFrame中加载的页面的风格
该样式可以在Javascript的帮助下从上级页面加载。
var cssFile = document.createElement("link")
cssFile.rel = "stylesheet";
cssFile.type = "text/css";
cssFile.href = "iFramePage.css";
然后将该CSS文件设置为受尊重的iFrame部分。
//to Load in the Body Part
frames['my_iFrame'].document.body.appendChild(cssFile);
//to Load in the Head Part
frames['my_iFrame'].document.head.appendChild(cssFile);
在这里,您可以在iFrame内用这种方式编辑页面的头部部分。
var $iFrameHead = $("#my_iFrame").contents().find("head");
$iFrameHead.append(
$("<link/>",{
rel: "stylesheet",
href: urlPath,
type: "text/css" }
));
我们可以在iframe中插入样式标签。 [也在这里发布...][1]
<style type="text/css" id="cssID">
.className
{
background-color: red;
}
</style>
<iframe id="iFrameID"></iframe>
<script type="text/javascript">
$(function () {
$("#iFrameID").contents().find("head")[0].appendChild(cssID);
//Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
});
</script>