使用textareas在iframe中显示实时结果,使用jQuery,将单独的textarea输入添加到iframes头部

我创建了两个文本区域。 一个用于HTML,一个用于CSS输入。 每个都有自己的ID。 使用我在网上找到的教程,我能够让这些textareas获取用户输入并实时显示在iFrame中。

然后我能够编写一些jQuery,它将来自textarea的用户输入ID为HTML,并将其添加到iFrames BODY标签,从而在iFrame中模拟HTML作为实时预览。 此外,jQuery使用布尔来检测textarea中是否有用户输入而没有html的ID(在这种情况下是一个ID为css的textarea),然后它将输入插入到STYLE标签内的iFrame的HEAD中因此,在iframe的头部添加了CSS。 在自己的样式标记中,允许用户在iFrame中生成CSS和HTML的实时输出。 一切都很好,坚如磐石。 我可以使用文本字段在我眼前生成实时HTML和CSS结果。

我的问题是,我需要在下面的jQuery代码中添加什么,以允许来自具有头部链接ID的单独textarea的输入被发送到iFrames HEAD? 我想要带有头链接ID的textarea,将用户输入发送到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  tags in the iFrame contents.find('head') // .find the HEAD... .append('') // then, add a  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  tags if ( $this.attr('id') === 'html') { body.html( $this.val() ); // Insert current value into the iFrames  tags }; if ( $this.attr('id') === 'css') { // Else the ID of HTML is not found... styleTag.text( $this.val() ); // Insert CSS into styleTag variable }; }); }); }); 

试试这个

  $(document).ready(function () { //DOC Ready, start of script // .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  tags in the iFrame styleTag = contents // styleTag variable says to... .find('head') // ...find the HEAD of the iframe... .append(''); // ...then, add a  tag to it. var scripts = ""+"
"+ +""+"
"+ +""+"
"; contents.find("head").append(scripts); // Detect textarea KeyUp during focus $('textarea').focus(function () { var $this = $(this); $this.keyup(function () { // If a user inputs data into the textarea with an ID of HTML, insert that input into the iFrame's tags if ($this.attr('id') === 'html') { body.html($this.val()); // Inster current value into the iFrames tags }; if ($this.attr('id') === 'css') { // Else the ID of HTML is not found... styleTag.text($this.val()); // ...Insert user input into the iFrames HEAD >> SCRIPT tags, via the styleTag variable }; }); }); });