Automatically adjust height to contents in Ace Cloud 9 editor

前端 未结 8 1997
孤街浪徒
孤街浪徒 2020-12-04 11:28

I\'m trying to add the Ace editor to a page, but I don\'t know how to get the height to be set automatically based on the length of its contents.

Ideally it would wo

8条回答
  •  佛祖请我去吃肉
    2020-12-04 11:41

    Update: See Dickeylth's answer. This all still works (and people still seem to find it useful), but the basic functionality is built into ACE now.


    To "automatically adjust height to contents in Ace Cloud9 editor", you just need to resize the editor to fit the div that contains it, whenever the content is edited. Assuming you started with

    ...

    var editor = ace.edit("editor");                   // the editor object
    var editorDiv = document.getElementById("editor");     // its container
    var doc = editor.getSession().getDocument();  // a reference to the doc
    
    editor.on("change", function() {
        var lineHeight = editor.renderer.lineHeight;
        editorDiv.style.height = lineHeight * doc.getLength() + "px";
        editor.resize();
    });
    

    You resize the div the editor lives in, then call editor.resize to get the editor to refill the div.

    If you paste content with long lines, with ACE set to wrap lines, the number of new lines and actual rendered lines will differ, so the editor will scroll. This code will fix that, but you will get horizontal scrolling instead.

    editor.getSession().setUseWrapMode(false)
    

提交回复
热议问题