How to apply CSS to inner Iframe element through parent window CSS class?

前端 未结 2 819
旧巷少年郎
旧巷少年郎 2020-12-15 23:06

I have a parent(main) page that has some iframe sections. And I want to apply css style to inner iframe element.

When I googling for it, I

相关标签:
2条回答
  • 2020-12-15 23:30

    If all your CSS is in external files something like this might work in your iframe.

    <script>
    window.onload = function() {
        Array.prototype.forEach.call(window.parent.document.querySelectorAll("link[rel=stylesheet]"), function(link) {
            var newLink = document.createElement("link");
            newLink.rel  = link.rel;
            newLink.href = link.href;
            document.head.appendChild(newLink);
        });
    };
    </script>
    

    It basically asks the parent for all the stylesheets then adds links to the iframe with the same references. If the iframe and the parent page are not at the same location on your server you'd have to manipulate the href appropriately.

    Also the code above probably only works on newer browsers.

    0 讨论(0)
  • 2020-12-15 23:36

    You can not directly apply styles to the inner IFrame element through parent window CSS class even though its domain is same as parent.

    As ,(All the iframe's domain is the same as the parent) ..

    Best thing you can do is ,to add your main style sheet to the IFrame using javascript or jquery.

     $(document).ready(function(){
            $('#myIframe').load(function(){
                $('#myIframe')
                        .contents().find("body")
                        .html("test iframe");
                $('#myIframe')
                    .contents().find("head")
                    .append($('<link rel="stylesheet" type="text/css" href="style.css">')
                );
            });
        });
    
    0 讨论(0)
提交回复
热议问题