【问题标题】:Creating a <style> tag in JavaScript, then accessing cssRules在 JavaScript 中创建 <style> 标记,然后访问 cssRules
【发布时间】:2011-02-04 21:36:20
【问题描述】:

我真的希望这不是一个愚蠢的问题......过去几个小时我一直在努力解决这个问题。

这本质上是对 Stack Overflow 其他地方的How to create a <style> tag with Javascript 的后续问题。 Tom 和 Michael 描述的技术在 IE、Firefox 和 Opera 中运行良好,并且几乎在 Chrome 和 Safari 中运行。问题是,在 Chrome 和 Safari 中,没有为样式表创建“cssRules”属性!其他浏览器创建一个“cssRules”属性(嗯,IE 创建一个“rules”属性,但你已经知道了)。

谁能解释如何为 iframe 创建一个样式表,以便在 Chrome 和 Safari 中为我提供“cssRules”属性?

我的目的是将样式表添加到我在网页中创建的 iframe,因为它似乎没有附带。后来,我希望将一些样式从封闭文档的样式表复制到 iframe 的样式表中,但我还没有做到。如果有人知道在我解决上述问题后这样做的任何注意事项,我会提前感激不尽。

【问题讨论】:

    标签: html css google-chrome safari stylesheet


    【解决方案1】:

    我在 Firefox 3.6、Chromium 8、Opera 11 (ubuntu 10.10) 中测试过

    temp.html:

    <style>
        body { background-color: blue; }
    </style>
    
     <body>
        Hello
    </body>
    

    index.html:

    <html>
    <head>
        <script>
            function test(){
                // your new <style> tag
                var stl = document.createElement("style");
                // its content
                stl.innerHTML = "body { background-color: red}";
    
                // getting iframe
                var myIframe = document.getElementById("myiframe");
    
                // apply new CSS to iframe
                myIframe.contentWindow.document.
                        getElementsByTagName('head')[0].appendChild(stl);
            }
        </script>
    </head>
    <body>
        <iframe id="myiframe" src="temp.html"></iframe>
        <button onclick="test()">
    </body>
    </html>
    

    当我单击按钮时,iframe 中的背景变为红色。

    附:抱歉,如果重复。我现在才打开您帖子中指向另一个主题的链接

    【讨论】:

    • 我说的是我创建所有内容的 iframe,而不是我从另一个页面加载它的 iframe。
    • 这就是我想告诉你的……有问题的 iframe 没有 src 属性——我自己创建了它的所有内容。此外,您的答案不会尝试访问样式表的 cssRules 属性,因此它没有解决问题。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-10
    相关资源
    最近更新 更多