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

查看:343
本文介绍了使用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天全站免登陆