使用 jQuery 将样式表附加到 iframe [英] Append a stylesheet to an iframe with jQuery

查看:25
本文介绍了使用 jQuery 将样式表附加到 iframe的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个 HTML 编辑器,类似于我现在正在输入的这个编辑器,输出如下.我正在使用 iframe 并将 $htmlTextBox.val() 转储到 iframe 的主体中.

I'm creating an HTML editor, similar to this one I'm typing in right now with the output below. I'm using an iframe and dumping the $htmlTextBox.val() into the body of the iframe.

我正在尝试在 iframe 中创建一个样式表,使其看起来和工作一样好.

I'm trying to create a stylesheet inside the iframe so that it looks as good as it works.

提前致谢!

$htmlTextBox.keyup(function(){
    SetPreview();
});   

function SetPreview()
{
    var doc = $preview[0].contentWindow.document;
    var $body = $("body", doc);

    $body.html($htmlTextBox.val());
}

推荐答案

虽然您可以与 iframe 的 document.styleSheets 进行交互,但传统的可靠方法是将样式表放在第一个位置(通过编写 iframe-src 指向具有所需样式表的空文档),或者使用 document.write() 将其放置到位.例如:

Whilst you can interact with an iframe's document.styleSheets, the old-school reliable way is either to have the stylesheet there in the first place (by writing an iframe-src to point to an empty document with the desired stylesheet), or put it in place with document.write(). For example:

<body>
    <iframe></iframe>
    <script type="text/javascript">

        var d= frames[0].document;
        d.open();
        d.write(
            '<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional //EN" "http://www.w3.org/TR/html4/loose.dtd">'+
            '<html><head><style type="text/css">'+
            'body { font-size: 200%; }'+
            '</style></head><body></body></html>'
        );
        d.close();

        d.body.innerHTML= '<em>Hello</em>';
    </script>
</body>

(这也会将 iframe 文档设置为标准模式,假设这是您想要的.)

(This will also set the iframe document to Standards Mode, assuming that's what you want.)

这篇关于使用 jQuery 将样式表附加到 iframe的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆