如何在外部域中设置iframe内部的样式? [英] How to style inside an iframe from an external domain?
问题描述
我有一个网站,其中包含来自3个不同域的3个iframe。每个iframe都在一个单独的页面上。将样式表应用于所有3个iframe的最佳方法是什么?
I have a website with 3 iframes embedded from 3 different domains. Each iframe is on a separate page. What is the best way to apply a style sheet to all 3 iframes?
谢谢!
推荐答案
这可以通过某些网站完成,但不是全部由于相同的原始政策。
允许它的是Twitter。这是重要的代码。
This can be done with some sites but not all due to "same origin policy". One that does allow it is Twitter. This is the important code.
$('#iframe').each(function(i){
var $head = $(this).contents().find('head');
if ($head.length){
$head.append($("<link/>", {
rel: "stylesheet",
href: "http://url.to.your.css",
type: "text/css"
}));
}
});
要在多个页面上使用相同的CSS,您将使用选择器来获取这三个iframe $('#iframe1,#iframe2,#iframe3')
但请记住,加载速度可能比另一个慢。
To use the same CSS on more than one page you would use a selector that picks up those three iframes $('#iframe1, #iframe2, #iframe3')
but bear in mind one may load slower than another.
如果它们位于不同的页面上并不重要,选择器将捕获存在的任何一个。
It doesn't matter if they are on different pages, the selector will catch whichever exists.
在下面的示例中,稍微缩小了默认的twitter标头,setInterval用于继续检查iframe是否已加载,一旦完成就被销毁。
In this following example, which shrinks the default twitter header slightly, setInterval is used to keep checking that the iframe has loaded, and once done it's destroyed.
HTML
<a class="twitter-timeline" style="height:600;" href="#" data-widget-id="your twitter widget id">Tweets</a>
JS
// twitter's own js
!function(d,s,id){var js,fjs=d.getElementsByTagName(s)[0],p=/^http:/.test(d.location)?'http':'https';if(!d.getElementById(id)){js=d.createElement(s);js.id=id;js.src=p+"://platform.twitter.com/widgets.js";fjs.parentNode.insertBefore(js,fjs);}}(document,"script","twitter-wjs");
// jquery to insert the css
$(function(){
var twitterCssCount = 0;
var twitterCss=setInterval(function(){
twitterCssCount++;
if (twitterCssCount>10) clearTimeout(twitterCss);
$('iframe.twitter-timeline').each(function(i){
var $head = $(this).contents().find('head');
if ($head.length){
$head.append($("<link/>", {
rel: "stylesheet",
href: "//url.to.your.css",
type: "text/css"
}));
clearTimeout(twitterCss);
}
});
},1000);
});
CSS文件的内容
.stream{
height:560px !important; /* because we're removing some of the header */
}
.timeline-header{
padding:0 0 5px 0;
}
.timeline-header .ic-twitter-badge{
border:0;
top:7px;
right:7px;
}
h1.summary, h2.byline{
display:none !important;
}
p.list-description{
padding:5px;
padding-bottom:0;
margin:0;
}
.root.customisable-border{
border-color:#666;
-webkit-border-radius: 0;
-moz-border-radius: 0;
border-radius: 0;
}
这篇关于如何在外部域中设置iframe内部的样式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!