【问题标题】:How to apply CSS to iframe using jQuery?如何使用 jQuery 将 CSS 应用于 iframe?
【发布时间】:2015-11-12 15:03:15
【问题描述】:

如何访问 iframe 并覆盖元素样式 "td.rank" ? 这是我到目前为止所得到的:

<script>

var head = $("#iframe11").contents().find("head");
var css = '<style type="text/css">' +
          'td.rank{background-color: #fc6b0a!important;}; ' +
          '</style>';
$(head).append(css);


</script>

<iframe src="http://www.example.com" id="iframe11" style="margin-left: 174px; width: 401px; border: 0px solid black; height: 358px; opacity: 0.85; margin-top: 23px;"></iframe>

当我使用“检查元素”打开代码时,我什至看不到 iframe 的 &lt;head&gt; 标记中的 CSS 代码部分。

【问题讨论】:

  • 试试这个...$("iframe").contents().find("td.rank").css("background-color", "#fc6b0a!important");
  • iframe 文档也必须位于相同的域和端口上。
  • 如果是 2 个不同的网站? @Jai
  • 那么昆汀已经回答了。 “安全政策”。当您在 iframe 中可用时,您无法触摸托管在其他域上的内容。

标签: javascript jquery html css iframe


【解决方案1】:
  1. 确保框架文档与框架文档位于同一来源,这样就不会出现security policy 违规。
  2. 移动脚本,使其出现在框架之后,以便在您尝试访问之前元素存在
  3. 将代码移动到一个函数中并将其用作框架的load 处理程序,以便在您尝试操作之前存在您要操作的 DOM

【讨论】:

    【解决方案2】:

    如果您想使用 jQuery 在 iframe 中添加 css 样式,请按照以下步骤操作...

    1.首先创建'index.html'文件并在其中添加以下代码

    <!DOCTYPE html>
    <html>
        <head>
            <script src="http://code.jquery.com/jquery-1.6.3.min.js"></script>
            <script>
            $(document).ready(function() {
                $('#iframe').load(function() {
                    $("#iframe").contents().find("head").append("<style>.text_color{color:red;}@page{margin:0;}</style>");  
                });
            });
            </script>
        </head>
        <body>
            <iframe src="iframe.html" id="iframe" name="iframe"></iframe>
        </body>
    </html>
    

    2。接下来创建另一个名为“iframe.html”的文件并添加以下代码

    <!DOCTYPE html>
    <html>
        <body>
            <div id="text"><span class="text_color">Content inside iframe goes here<span></div>
        </body>
    </html>
    

    3.接下来运行“index.html”文件,现在看到“iframe 内的内容在此处”文本颜色将变为红色

    【讨论】:

      猜你喜欢
      • 2010-09-18
      • 2014-01-14
      • 1970-01-01
      • 1970-01-01
      • 2011-04-12
      • 1970-01-01
      • 2019-06-04
      • 2013-01-15
      相关资源
      最近更新 更多