Using CSS to affect div style inside iframe

前端 未结 13 1542
失恋的感觉
失恋的感觉 2020-11-22 07:00

Is it possible to change styles of a div that resides inside an iframe on the page using CSS only?

相关标签:
13条回答
  • 2020-11-22 07:20

    In short no.

    You can not apply CSS to HTML that is loaded in an iframe, unless you have control over the page loaded in the iframe due to cross-domain resource restrictions.

    0 讨论(0)
  • 2020-11-22 07:22

    The quick answer is: No, sorry.

    It's not possible using just CSS. You basically need to have control over the iframe content in order to style it. There are methods using javascript or your web language of choice (which I've read a little about, but am not to familiar with myself) to insert some needed styles dynamically, but you would need direct control over the iframe content, which it sounds like you do not have.

    0 讨论(0)
  • 2020-11-22 07:22

    Use Jquery and wait till the source is loaded, This is how I have achieved(Used angular interval, you can use javascript setInterval method):

    var addCssToIframe = function() {
        if ($('#myIframe').contents().find("head") != undefined) {
            $('#myIframe')
                    .contents()
                    .find("head")
                    .append(
                            '<link rel="stylesheet" href="app/css/iframe.css" type="text/css" />');
            $interval.cancel(addCssInterval);
        }
    };
    var addCssInterval = $interval(addCssToIframe, 500, 0, false);
    
    0 讨论(0)
  • 2020-11-22 07:22

    Not possible from client side . A javascript error will be raised "Error: Permission denied to access property "document"" since the Iframe is not part of your domaine. The only solution is to fetch the page from the server side code and change the needed CSS.

    0 讨论(0)
  • 2020-11-22 07:23

    You need JavaScript. It is the same as doing it in the parent page, except you must prefix your JavaScript command with the name of the iframe.

    Remember, the same origin policy applies, so you can only do this to an iframe element which is coming from your own server.

    I use the Prototype framework to make it easier:

    frame1.$('mydiv').style.border = '1px solid #000000'
    

    or

    frame1.$('mydiv').addClassName('withborder')
    
    0 讨论(0)
  • 2020-11-22 07:25

    Yes. Take a look at this other thread for details: How to apply CSS to iframe?

    var cssLink = document.createElement("link");
    cssLink.href = "style.css";  
    cssLink.rel = "stylesheet";  
    cssLink.type = "text/css";  
    frames['frame1'].document.body.appendChild(cssLink); 
    
    0 讨论(0)
提交回复
热议问题