Fancybox add stylesheet to parent page

2019-06-12 22:00发布

问题:

I have this code to add a stylesheet to a page in a fancybox iframe. Can I do the same to the parent page?

I have tried this but it didn't work...

window.parent.changeStyles(stylesheet);

function changeStyles(styles) { $("", { rel: "stylesheet", type: "text/css", href: styles }).appendTo("head"); };

            $('.change-styles').on('click',function(){                              
                var stylesheet = $(this).attr('href');
                changeStyles(stylesheet);


                return false
            });

回答1:

First, define a parent file:

<html>
<head></head>
<body>
    <iframe src="iframe.html"></iframe>
</body>
</html>

Then the iframe file as iframe.html:

<html>
<head>

<script>

function addCSSToParent(url) {
    var link = document.createElement('link');
    link.rel = 'stylesheet';
    link.href = url;
    link.type = 'text/css';
    window.parent.document.getElementsByTagName('head')[0].appendChild(link);
}

// Add some CSS
addCSSToParent('some.css');

</script>
</head>

<body>This is the iframe.</body>
</html>

The addCSSToParent() will add a new DOM element into the head of its parent with the given URL. Make sure to run this in a server environment, because accessing the parent worked but gave a few security errors in Chrome.