gpt4 book ai didi

javascript - 如何在外部域的 iframe 中设置样式?

转载 作者:行者123 更新时间:2023-11-28 12:15:16 29 4
gpt4 key购买 nike

我有一个网站,其中嵌入了来自 3 个不同域的 3 个 iframe。每个 iframe 都在一个单独的页面上。将样式表应用于所有 3 个 iframe 的最佳方法是什么?

谢谢!

最佳答案

这可以在一些站点上完成,但由于“同源策略”,并非所有站点都可以。一个允许它的是 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,您可以使用选择器来选择这三个 iframe $('#iframe1, #iframe2, #iframe3') 但请记住,可能加载速度比另一个慢。

如果它们在不同的页面上并不重要,选择器将捕捉存在的那个。

在下面的示例中,它稍微缩小了默认的 Twitter header ,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;
}

关于javascript - 如何在外部域的 iframe 中设置样式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23873407/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com