如何让ace编辑器调整到其父div

use*_*521 17 html css ace-editor

我在另一个div中有ace div,我希望ace编辑器将它的宽度和高度调整为父div.我调用editor.resize()但没有任何反应.

<!DOCTYPE html>
<html lang="en" style="height: 100%">
<head>
<title>ACE in Action</title>
<style type="text/css" media="screen">
    #editor { 
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
        height: 100px;
    }
</style>
</head>
<body style="height: 100%">
<div style="background-color: red; height: 100%; width: 100%;">
<div id="editor">function foo(items) {
    var x = "All this is syntax highlighted";
    return x;
}</div>
</div>

<script src="ace-builds/src-noconflict/ace.js" type="text/javascript" charset="utf-8"></script>
<script>
    var editor = ace.edit("editor");
    editor.setTheme("ace/theme/monokai");
    editor.getSession().setMode("ace/mode/javascript");

    editor.resize();
</script>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

小智 10

你可以用两种方式达到你想要的效果.我创建了一个jsfiddle,显示用于将ace编辑器的大小调整为其容器的css和javascript.

使用的css是为了使编辑器占用容器的宽度和高度,这样editor.resize()才能正确计算编辑器的大小.

我推荐以下内容editor.resize()来开展工作.

<style type="text/css" media="screen">
    #editor {
        width: 100%;
        height: 100%;
    }
</style>
Run Code Online (Sandbox Code Playgroud)

但是,如果您想维护使用当前的css,#editor则以下内容将起作用.

<style type="text/css" media="screen">
    #editor {
        position: absolute; /* Added */
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
   }
</style>
Run Code Online (Sandbox Code Playgroud)

并添加position: relative;到容器中,以便绝对定位的编辑器正确定位在其容器内.至于这是如何工作的,我建议您在相对定位内进行绝对定位.


Mar*_*uez 9

我用简单的 CSS 让它工作:

#container{
    height:80vh;
}

#editor {
    width: 100%;
    height: 100%;
    position: relative;
}
Run Code Online (Sandbox Code Playgroud)

关键属性是position:relative,覆盖 ace 编辑器的默认值position:absolute,这会导致父容器无法调整其内容。

<div id="container">
    <pre id="editor">
        &#x3C;div&#x3E;
        &#x9;&#x9;this is a div
        &#x9;&#x3C;/div&#x3E;
    </pre>
</div>

<script>
    $(document).ready(function() {
        var editor = ace.edit("editor");
        editor.setTheme("ace/theme/TextMate");
        editor.session.setMode("ace/mode/html");
    });
</script>
Run Code Online (Sandbox Code Playgroud)


小智 5

您可以通过以下方式实现。例如,运行代码片段。

var editor = ace.edit("editor");
        editor.setTheme("ace/theme/tomorrow_night");
        editor.session.setMode("ace/mode/xml");
        editor.session.setUseSoftTabs(true);
Run Code Online (Sandbox Code Playgroud)
#parent {
    width:50%;
    height: 600px;
    display:inline-block;
    position:relative;
}
#editor {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.3.3/ace.js"></script>
<html>
   <body>
      <div id="parent">
          <div id="editor"></div>
      </div>
   </body>
</html>
Run Code Online (Sandbox Code Playgroud)