Append a stylesheet to an iframe with jQuery
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.
I'm trying to create a stylesheet inside the iframe so that it looks as good as it works.
Thanks in advance!
$htmlTextBox.keyup(function(){
SetPreview();
});
function SetPreview()
{
var doc = $preview[0].contentWindow.document;
var $body = $("body", doc);
$body.html($htmlTextBox.val());
}
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>
(This will also set the iframe document to Standards Mode, assuming that's what you want.)
Followup:
HTML
<iframe id="message" name="message" />
jQuery
setTimeout(function() {
var $head = $("#message").contents().find("head");
$head.append($("<link/>",
{ rel: "stylesheet", href: url, type: "text/css" }
));
}, 1);
我们可以将样式标签插入到iframe中。
<style type="text/css" id="cssID">
.className
{
background-color: red;
}
</style>
<iframe id="iFrameID"></iframe>
<script type="text/javascript">
$(function () {
$("#iFrameID").contents().find("head")[0].appendChild(cssID);
//Or $("#iFrameID").contents().find("head")[0].appendChild($('#cssID')[0]);
});
</script>
链接地址: http://www.djcxy.com/p/23794.html
上一篇: Python装饰只是语法糖?
下一篇: 用jQuery将样式表附加到iframe