【发布时间】:2014-05-09 13:23:19
【问题描述】:
我创建了两个文本区域。一种用于 HTML,一种用于 CSS 输入。每个人都有自己的 ID。使用我在网上找到的教程,我能够让这些文本区域接受用户输入并将其实时显示在 iFrame 中。
然后我能够编写一些 jQuery,它从文本区域获取用户输入,ID 为 HTML,并将其添加到 iFrames BODY 标签,因此在 iFrame 中模拟 HTML 作为实时预览。此外,jQuery 使用 boolean 来检测文本区域中是否有用户输入而没有 html 的 ID(在本例中是 ID 为 css 的文本区域),然后将输入插入到 STYLE 标记内的 iFrame 的 HEAD ,因此将 CSS 添加到 iframe 的头部。在它自己的样式标签中,并允许用户在 iFrame 内生成其 CSS 和 HTML 的实时输出。一切都很好,坚如磐石。我能够使用文本字段在我眼前生成实时 HTML 和 CSS 结果。
我的问题是,我需要在下面的 jQuery 代码中添加什么,以允许将来自具有标题链接 ID 的单独文本区域的输入发送到 iFrames HEAD?我想要带有头链接 ID 的文本区域,将用户输入发送到 iframe 的 HEAD 这将允许该工具的用户链接到他们自己的外部样式表和/或 jquery/javascript 库等。
感谢大家的帮助。我有我的 jQuery 脚本。请告诉我你的想法。
回答:使用 jQuerys .clone 方法将父文档头部的 jQuery LINKS 和 SCRIPT 标签添加到 iFrames 头部更容易。下面是工作代码。
$(document).ready(function()
{
// .Grid Window Height
$('.grid').height( $(window).height() );
// Declaring the Output Window Variables
var frame = $('iframe'); // The iFrame variable itself
contents = frame.contents(); // Declares the variable of contents which is the iFrames content
body = contents.find('body'); //body variable finds the <BODY></BODY> tags in the iFrame
contents.find('head') // .find the HEAD...
.append('<style type=text/css></style>') // then, add a <STYLE></STYLE> tag to it...
styleTag = contents.find("style");
// Append Parent Document HEAD Elements with the class of wst to the iFrames HEAD
var jq = $(".wst").clone();
frame.contents()
.find("head")
.append(jq);
// Detect textarea KeyUp during focus
$('textarea').on("focus", function(e)
{
var $this = $(e.target);
$(document).keyup(function()
{
// If the ID of HTML is found, inster the HTML into the iFrame's <BODY></BODY> tags
if ( $this.attr('id') === 'html')
{
body.html( $this.val() ); // Insert current value into the iFrames <BODY></BODY> tags
};
if ( $this.attr('id') === 'css')
{
// Else the ID of HTML is not found...
styleTag.text( $this.val() ); // Insert CSS into styleTag variable
};
});
});
});
【问题讨论】:
标签: javascript jquery html iframe textarea