开发者

Creating a <style> tag in JavaScript, then accessing cssRules

开发者 https://www.devze.com 2023-02-08 20:51 出处:网络
I really hope this isn\'t a stupid question...I\'ve been beating my head against the wall for the last few hours trying to solve it.

I really hope this isn't a stupid question...I've been beating my head against the wall for the last few hours trying to solve it.

This is essentially a followup question to How to create a <style> tag with Javascript, elsewhere on Stack Overflow. The techniques described by Tom and Michael work great in IE, Firefox, and Opera, and almost work in Chrome and Safari. The problem is, in Chrome and Safari, no "cssRules" property is created for the style sheet! The other browsers create a "cssRules" property (well, IE creates a "rules" property, but you knew that already).

Can anyone explain how to create a style sheet for an iframe that'll give me a "cssRules" pro开发者_Python百科perty in Chrome and Safari?

My intention is to add a style sheet to an iframe that I created in my web page, since it doesn't seem to come with one. Later, I hope to copy some of the styles from the enclosing document's style sheet to the iframe's style sheet, but I haven't gotten there yet. If anyone knows of any caveats to doing that once I've solved the above problem, I'd be grateful in advance.


I've tested in 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>

When I click the button, background in iframe becomes red.

P.S. Sorry if it is repeating. I've only now opened the link in your post to another topic

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号