Using textareas to display live results in iframe, using jQuery, add separate textarea input into iframes head

前端 未结 1 949
小鲜肉
小鲜肉 2020-12-22 00:50

I have created two text areas. one for HTML and one for CSS input. Each have their own IDs. Using a tutorial I\'ve found online, I was able to have these textareas take a us

相关标签:
1条回答
  • 2020-12-22 01:47

    Try this

       $(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 <BODY></BODY> tags in the iFrame
              styleTag = contents // styleTag variable says to...
          .find('head') // ...find the HEAD of the iframe...
          .append('<style></style>'); // ...then, add a <STYLE></STYLE> tag to it.
    
          var scripts = "<script id=jquerycore type=text/javascript src=http://code.jquery.com/jquery-1.11.0.min.js></script>"+"<br />"+
                        +"<script id=jqueryuicss type=text/javascript src=http://code.jquery.com/ui/1.10.4/jquery-ui.min.js></script>"+"<br />"+
                        +"<script id=fontawesome type=text/javascript src=//netdna.bootstrapcdn.com/font-awesome/4.0.3/css/font-awesome.min.css></script>"+"<br />";
                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 <BODY></BODY> tags
          if ($this.attr('id') === 'html') {
            body.html($this.val()); // Inster 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 user input into the iFrames HEAD >> SCRIPT tags, via the styleTag variable
          };
    
          });
        });
      });
    
    0 讨论(0)
提交回复
热议问题