HTML Editor With iFrame Not Working

时间:2016-04-21 22:19:27

标签: javascript jquery html css iframe

* {
    padding: 0;
    margin: 0;
}
body {
    font-family: sans-serif;
}

.grid {
    width: 50%;
    float: left;
    padding: 30px 50px;

}

.container {
    background: #e3e3e3;
}


textarea {
    width: 100%;
    height: 200px;
    resize: none;
    margin-top: 20px;
    margin-bottom: 50px;
}

iframe {
    border-style: solid;
    border-color: aqua;
    height: 1000px;
    width: 100%;
    display: block;
}
<!DOCTYPE HTML>
<hmtl>
    <head>
        <link rel = "stylesheet" type = "text/css" href = "style.css">
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
        
       <script>
            (function() {
$('grid').height($(window).height() );

var frame = $('iframe');
var contents = frame.contents();
var body = contents.find('body')
var styleTag = contents.find('head').append('<style></style>').children('style');

$('textarea').focus(function() {
var $this = $(this);
$this.keyup(function() {
if ($this.attr('id') == 'html') {
body.html($this.val() );
}
else
{
styleTag.text($this.val() );
}
});
});
});
            
</script>
    </head>
    
    <body>
        <div class = "container grid">
            <form>
                <h2>HTML</h2>
                <textarea id = "html"></textarea>
                
                <h2>CSS</h2>
                <textarea id = "css"></textarea>
            </form>
        </div>
        
        <div class = "output grid">
            <iframe></iframe>
        </div>
    </body>
</hmtl>

I'm trying to make a simple online html editor (like codepen) and, the result is not showing up. I have tried to solve this problem for more than an hour! Please Help! This problem is bugging me, and the internet won't help! I'm suspecting the jQuery has issues, but it doesn't seem like it

1 个答案:

答案 0 :(得分:1)

首先关闭脚本是在头部标签而不是关闭身体标签。这意味着在添加任何内容之前运行脚本。

如果你的意图是将脚本保留在head标签中,则需要将你的函数放在DOMContentLoaded事件监听器中。

document.addEventListener('DOMContentLoaded', function() {
  // your script
})

JQuery等同于......

$(document).ready(function() {
  // your script
})

and that's all you need to get your editor working.

如果您想将高级代码编辑器与广泛的API集成,我建议您查看CodeMirrorAce Editor

我开发了kodeWeave,我在平板电脑上在线和离线使用它。它有一些演示,如代码编辑器(CodeMirror),分割器(来自jqxSplitter等)。

这些只是一些额外的提示,可帮助您开始制作代码游乐场。

如果您想了解有关how to make your own coding playground的更多信息,我还制作了一个视频。