【问题标题】:Changing CSS of element inside an iframe using data attribute使用数据属性更改 iframe 内元素的 CSS
【发布时间】:2021-06-18 12:14:52
【问题描述】:

我的 HTML 文档中有一个 iframe。此iframe 具有数据属性“data-search-id”,即“mainline-top”。如何在 iframe 之外使用 JavaScript 来更改具有类“base-top”的元素的颜色。我应该使用数据属性还是有其他方法?请注意,我无法将 id 或类添加到 iframe,它是从其他地方加载的。

<!DOCTYPE html>
<html lang="en">
<meta charset="UTF-8">
<title>Page Title</title>

<script src="https://code.jquery.com/jquery-3.6.0.min.js "integrity="sha256-/xUj+3OJU5yExlq6GSYGSHk7tPXikynS7ogEvDej/m4=" crossorigin="anonymous"></script>
<body>

    <iframe data-search-id="mainline-top">
        
        <style>.base-top{color: #red;}</style>
        
        <div class="base-top">Stuff</div>

    </iframe> 

<script>
     $('.base-top.).css(color, "blue");
</script>

</body>
</html>

【问题讨论】:

  • iframe 来自另一个域,但我想我可以编辑它,我只需要使用 data 属性访问 iframe
  • var iframe = document.querySelctor("[data-search-id='mainline-top']");或类似的东西?
  • “iframe 来自另一个域”。然后由于浏览器安全限制,您无法使用父页面中的脚本进入其中

标签: javascript html jquery css iframe


【解决方案1】:

您可以在 iframe 中插入样式标签。

<iframe data-search-id="mainline-top" id="myIframe">
        
        <style>.base-top{color: red;}</style>
        
        <div class="base-top">Stuff</div>

    </iframe> 
<style type="text/css" id="mycss">.base-top{color: blue;}</style>
<script type="text/javascript">
    $(function () {
        $('*[data-search-id="mainline-top"]').contents().find("head")[0].appendChild(mycss);
    });
</script>

【讨论】:

  • 完美,如何使用 iframe 的数据属性?我不能给 iframe 一个 ID,否则我会
  • 使用可以使用:$('*[data-search-id="mainline-top"]')
  • 当我在 jsfiddle 中尝试时,它似乎不起作用
  • 如果 iframe 的来源有不同的来源或协议(http://、https://),那么您根本无法使用任何东西访问它。
  • 如果我能让您的示例先运行,那么我可以对其进行测试。有没有办法运行你的代码 sn-p 来尝试一下?当我将其复制/粘贴到 JS fiddle 时,contents().find("head") 部分不起作用。但是做 $('*[data-search-id="mainline-top"]').hide();确实有效
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-04
  • 1970-01-01
  • 1970-01-01
  • 2020-04-15
  • 2017-05-20
相关资源
最近更新 更多