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

这本质上是How to create a <style> tag with Javascript后续问题,在Stack Overflow的其他地方。 Tom和Michael描述的技术在IE,Firefox和Opera中非常有效,而在Chrome和Safari中几乎可以使用。问题是,在Chrome和Safari中,没有为样式表创建“ cssRules”属性!其他浏览器创建“ cssRules”属性(IE会创建“ rules”属性,但是您已经知道了)。

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

我的目的是向我在网页中创建的iframe中添加样式表,因为该样式表似乎没有。稍后,我希望将一些样式从随附文档的样式表复制到iframe的样式表,但是我还没有到那里。如果我解决了上述问题,如果有人知道这样做的任何警告,请提前感谢。

最佳答案

我已经在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中的背景变为红色。

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

关于html - 在JavaScript中创建<style>标记,然后访问cssRules,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4903175/

10-12 00:09
查看更多