我有一个网站,从3个不同的域嵌入3个iframe。每个iframe都在一个单独的页面上。将样式表应用于所有3个框架的最佳方法是什么?
谢谢!
这可以在某些站点上实现,但并非所有站点都是由于"同源策略"。其中一个允许这样做的是Twitter。这是重要的代码。
$('#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,您可以使用选择器来挑选这三个iframes $('#iframe1, #iframe2, #iframe3')
,但请记住其中一个可能比另一个加载速度慢。
无论它们是否在不同的页面上,选择器将捕获存在的。
在下面这个示例中,它稍微缩小了默认的twitter头,setInterval用于持续检查iframe是否已经加载,一旦加载完成,它将被销毁。
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;
}