jquery将所有样式表插入到iframe中

发布于 2024-08-06 06:06:17 字数 667 浏览 2 评论 0原文

如何将父窗口的所有样式表插入 iframe 的头部(同域)?

我尝试的代码基于类似的问题:

function () {
    var d = frames[0].document;
    var stylesheets = $("link").outerhtml;
    d.open();
    d.write(
    '<html><head>'+
    stylesheets + 
    '<style type="text/css">'+
    '<\/style><\/head><body><\/body><\/html>'
    );
    d.close();
}

显然这在 IE 之外不起作用。提前致谢。

编辑:根据安东尼的回答尝试:

    $("link[type='text/css']").each(function() {
        var stylesheet = $(this).clone();                                    
        $("iframe").contents().find("head").append(stylesheet);
    });

How can I insert all of a parent window's stylesheets into an iframe's head(samedomain)?

My attempted code based on a similar question:

function () {
    var d = frames[0].document;
    var stylesheets = $("link").outerhtml;
    d.open();
    d.write(
    '<html><head>'+
    stylesheets + 
    '<style type="text/css">'+
    '<\/style><\/head><body><\/body><\/html>'
    );
    d.close();
}

Clearly this does not work outside of IE. Thanks in advance.

Edit: Attempt based on Anthony's answer:

    $("link[type='text/css']").each(function() {
        var stylesheet = $(this).clone();                                    
        $("iframe").contents().find("head").append(stylesheet);
    });

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

伏妖词 2024-08-13 06:06:17

所选答案的一个问题是它使用 .html(),它仅返回该元素的内部 html 内容,而不是元素本身。这是一个可行的解决方案:

$("link[type='text/css']").clone().appendTo($("iframe").contents().find("head"));

An issue with the selected answer is that it uses .html(), which returns only the inner html contents of that element, not the element itself. Here is a working solution:

$("link[type='text/css']").clone().appendTo($("iframe").contents().find("head"));
待天淡蓝洁白时 2024-08-13 06:06:17
$("link[type='text/css']").each(function() {
     var stylesheet = $(this).html();
     $("iframe").contents().find("head").append(stylesheet);
     });
$("link[type='text/css']").each(function() {
     var stylesheet = $(this).html();
     $("iframe").contents().find("head").append(stylesheet);
     });
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文