【问题标题】:How to style inside an iframe from an external domain?如何在外部域的 iframe 内设置样式?
【发布时间】:2014-07-15 10:06:24
【问题描述】:

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

谢谢!

【问题讨论】:

  • 有几种不同的方法...使用 javascript 设置域属性或使用 CORS 允许访问 DOM,使用查询字符串将信息发送到 iframe,您是否尝试过其中任何一种选项?
  • 感谢马特,我第一次听说。你知道任何好的例子/教程吗?给我一个正确的方向!
  • 我建议执行一些 Google-fu 并编写一些代码,然后再搜索一些代码,如果遇到困难,在搜索和编码之后再返回一些代码。

标签: javascript php css iframe


【解决方案1】:

由于“同源政策”,某些网站可以做到这一点,但并非全部。 一个允许它的是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 标头,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;
}

【讨论】:

    猜你喜欢
    • 2012-11-02
    • 1970-01-01
    • 2010-09-15
    • 1970-01-01
    • 2014-09-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多