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

时间:2015-02-28 18:59:30

标签: 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>

5 个答案:

答案 0 :(得分:10)

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

使用的css是为了使编辑器占用容器的宽度和高度,以便editor.resize()可以正确计算编辑器应该的大小。

我建议使用以下内容让editor.resize()正常工作。

<style type="text/css" media="screen">
    #editor {
        width: 100%;
        height: 100%;
    }
</style>

但是,如果您想继续使用#editor的当前css,则以下内容将有效。

<style type="text/css" media="screen">
    #editor {
        position: absolute; /* Added */
        top: 0;
        right: 0;
        bottom: 0;
        left: 0;
   }
</style>

并将position: relative;添加到容器中,以便绝对定位的编辑器正确放置在其容器内。至于这是如何工作的,我建议您Absolute positioning inside relative positioning.

答案 1 :(得分:3)

使用jquery-ace我通过使用以下方式设置了这个:

    $('#php_code').ace({
        theme: 'chrome',
        lang: 'php',
        width: '100%',
        height: '300px'
    })

答案 2 :(得分:3)

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

var editor = ace.edit("editor");
        editor.setTheme("ace/theme/tomorrow_night");
        editor.session.setMode("ace/mode/xml");
        editor.session.setUseSoftTabs(true);
#parent {
    width:50%;
    height: 600px;
    display:inline-block;
    position:relative;
}
#editor {
    position: absolute;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
}
<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>

答案 3 :(得分:3)

我可以使用简单的CSS:

#container{
    height:80vh;
}

#editor {
    width: 100%;
    height: 100%;
    position: relative;
}

键属性是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>

答案 4 :(得分:1)

将其设置重新设置为浏览器的默认设置,该设置可以适应父容器。

#editor {
    width: inherit !important;
}

我正在对reactjs使用react-ace包装器。 对于任何覆盖某些默认值的ace包装器来说,这都是有益的。

相关问题