【问题标题】:How to overwrite a div (html body, sets background) in an iFrame from local domain using jquery?如何使用 jquery 从本地域覆盖 iFrame 中的 div(html 正文,设置背景)?
【发布时间】:2018-01-24 07:40:01
【问题描述】:

我试图从 iFrame 中删除的 CSS(phpbb 中的 colours.css)

html, body {
    color: #536482;
    background: url("../path/to/background.jpg") repeat-x #8fe909;
}

iFrame:

<iframe id="commentframe" scrolling="no" name="commentframe" onload="iframeLoaded()" src="/forum/viewtopic.php?f=13&t=10">

这也包含在一个名为 #commentdiv 的 div 中,只是为了更容易处理 span 区域。这里也是 iframe 加载的,虽然我认为这无关紧要,人们经常要求与正在进行的代码相关的任何内容

<script type="text/javascript">
  function iframeLoaded() {
      var iFrameID = document.getElementById('commentframe');
      if(iFrameID) {
            // here you can make the height, I delete it first, then I make it again
            iFrameID.height = "";
            iFrameID.height = iFrameID.contentWindow.document.body.scrollHeight + "px";
      }   
  }
</script>

据我了解,我需要使用 .has() jquery 函数通过在某处指定 CSS 类来完成此任务

.commentsbg {
    background-color: transparent;
    background: transparent;
}

那么 .has 的功能是这样的。

  <script type="text/javascript">
  $("body").has("iframe").addClass('commentsbg');
  </script>

我也试过

  <script type="text/javascript">
  $("commentdiv").has("iframe").addClass('commentsbg');
  </script>

以及在我的 .on('load', function)s 字符串中尝试它们。老实说,我对这些应该去哪里感到非常困惑。 js/jquery 是否进入 CSS 文件(这曾经发生过吗?)... CSS 是否进入 colours.css(iframe 的原始 css 文件)?我对这个很迷茫并且已经做了很长一段时间了。

【问题讨论】:

  • 首先尝试在您的样式 css 文件中使用纯 css .. 尝试如下操作:iframe&gt;body{ background-color: red !important } 用其他东西替换红色,如果这不起作用然后使用 js,重要的是是!important标志

标签: javascript jquery html css iframe


【解决方案1】:

有几点要评论:

  <script type="text/javascript">
  $("commentdiv").has("iframe").addClass('commentsbg');
  </script>

这里您忘记了 commentDiv 的标识符或类,因此您的函数将不起作用(# 用于 id. 用于类):

  $("#commentdiv").has("iframe").addClass('commentsbg');

$(".commentdiv").has("iframe").addClass('commentsbg')

但是,我认为您没有正确接近您想要实现的目标。您可以直接对您想要的标签进行操作。

之后,CSS 属性应该修改 CSS,因此最好在加载时向您的 &lt;iframe&gt; 添加一个类,并在您的 CSS 中更改它的属性。

你的代码是多余的,有background: transparentbackground-color: transparent,最好用:

.commentsbg {
    background-color: transparent !important;
}

但是,您可以直接对 CSS 中的 &lt;iframe&gt; 执行操作,添加 !important 以删除默认样式。

为了简化和总结事情,你应该修改你的 iframe 的背景,首先在你的 CSS 中(如果需要,添加 !important,因为 JavaScript 会加载更多你的网站)。

如果这不起作用,请尝试在需要时添加一个类(例如onload)并修改它的 CSS。

【讨论】:

  • 感谢您抽出宝贵的时间让我知道所讨论的错误出了什么问题,还让我知道了我做错的许多其他事情并让我正确处理它们。不会再忘记这些事情了。 :) 现在我的牙齿陷入了这一切。
  • @Rogerjwilkinson 谢谢,如果您有更多问题,请不要犹豫,问。如果您的疑问已解决,请标记为已接受以关闭问题。祝你有美好的一天
  • 嗯,如果我没看错的话, !important 一个人应该这样做吗?
  • 如果您对标签的行为正确,则应该如此。
  • 是否有机会详细说明这部分“如果这不起作用,请尝试在需要时添加一个类(例如 onload)并修改它的 CSS。” !important 不幸的是似乎没有什么不同。
猜你喜欢
  • 2017-06-14
  • 2021-09-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-13
  • 2021-10-01
相关资源
最近更新 更多