【问题标题】:Fancybox add stylesheet to parent pageFancybox 将样式表添加到父页面
【发布时间】:2012-02-25 06:51:38
【问题描述】:

我有这段代码可以将样式表添加到fancybox iframe 中的页面。我可以对父页面做同样的事情吗?

我试过了,但是没用……

window.parent.changeStyles(stylesheet);

函数更改样式(样式){ $("", { rel: "样式表", 类型:“文本/css”, href: 样式 }).appendTo("头"); };

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


                return false
            });

【问题讨论】:

    标签: jquery fancybox parent


    【解决方案1】:

    首先,定义一个父文件:

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

    然后iframe文件为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>
    

    addCSSToParent() 将使用给定的 URL 将新的 DOM 元素添加到其父元素的头部。确保在服务器环境中运行它,因为访问父级有效,但在 Chrome 中出现了一些安全错误。

    【讨论】:

    • 这并不针对父页面,但这是我需要的。谢谢
    • 您的意思是 JS 在 iframe 中运行并且您希望它向父级添加 CSS?
    • 对不起。是的。没有解释得太清楚
    • 这在大多数浏览器中运行良好,除了 IE8。我不得不为 IE 添加 createStyleSheet(stylesheet) 函数。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多