Fancybox add stylesheet to parent page

时间秒杀一切 提交于 2019-12-23 05:58:34

问题


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.



来源:https://stackoverflow.com/questions/9115351/fancybox-add-stylesheet-to-parent-page

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!