How to apply CSS to inner Iframe element through p

2020-02-27 23:45发布

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 found many post relate to this topic but they all suggest to use jquery/javascript to apply CSS to inner elements.

Is it possible to apply css style to inner iframe element through parent window(main page) CSS class?

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

标签: html css iframe
2条回答
不美不萌又怎样
2楼-- · 2020-02-28 00:38

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.

查看更多
劳资没心,怎么记你
3楼-- · 2020-02-28 00:44

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">')
            );
        });
    });
查看更多
登录 后发表回答