【问题标题】:JavaScript style body outside iframeiframe 外的 JavaScript 样式主体
【发布时间】:2018-04-22 20:30:56
【问题描述】:

如何在 iFrame 最内层的 body 标签内使用 JavaScript 设置最外层的 body 标签的样式?

<html>
  <head>
  </head>
  <body>
    <div id="ad_tag" style="width: 1px; height: 1px;">
      <div id="ad_container" style="border: 0pt none;">
        <iframe id="ad_iframe" title="title" name="name" scrolling="no" marginwidth="0" marginheight="0" style="border: 0px none; vertical-align: bottom;" srcdoc="" width="1" height="1" frameborder="0">
          <html>
            <head>
            </head>
            <body topmargin="0" leftmargin="0" marginwidth="0" marginheight="0">
              <script>
              parent.document.body.style.background = "url('https://news.nationalgeographic.com/content/dam/news/photos/000/676/67655.jpg') no-repeat top center fixed #ffffff";
              </script>
            </body>
          </html>
        </iframe>
      </div>
    </div>
    <div id="content">
    </div>
  </body>
</html>
  • 在这种特定情况下:
    • 不允许直接编辑属性或样式,现有的都是预设的。
    • 只能编辑最内层主体的子元素。
    • 目标是使用 Google DFP 提供背景图片。

【问题讨论】:

  • iframe是否有权限访问父文档?
  • @CertainPerformance,是的。

标签: javascript css iframe google-dfp skin


【解决方案1】:

最好的方法是使用框架中的发布消息,父(站点)将通过侦听器执行。 所以你的 iframe 应该包含一些类似的代码:

<script>
     window.parent.postMessage({
        'func': 'changeBackground',
        'message': ''
    }, "*");
</script>

你的父母(网站)应该包含一个像这样的监听器:

<script type="text/javascript">
if (window.addEventListener) {
    window.addEventListener("message", onMessage, false);       
}
else if (window.attachEvent) {
    window.attachEvent("onmessage", onMessage, false);
}



function onMessage(event) {
    var data = event.data;
    if (typeof(window[data.func]) == "function") {
        window[data.func].call(null, data.message);
    }
}

function changeBackground(message) {

    $('div#backgroundwrapper').css({
        'background-image': 'url("https:/example.com/example.jpg")',
    $('div#backgroundwrapper').click();
        var win = window.open( '%%CLICK_URL_ESC%%%%DEST_URL%%', '_blank');
    win.focus();
    });
}
</script>

在我的示例中,它会将图像文件作为背景放在 ID 为 backgroundwrapper 的 div 上。我的示例使用 jQuery 来更改 CSS 并添加点击标签,但也可以不使用它。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2013-01-05
    • 1970-01-01
    • 2020-09-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-15
    相关资源
    最近更新 更多