lim*_*oop 61 javascript ace-editor
我正在尝试将Ace编辑器添加到页面中,但我不知道如何根据其内容的长度自动设置高度.
理想情况下它会起作用,所以当内容改变时,重新计算高度,但我会对页面加载时设置的高度感到满意.
对于JavaScript新手,有人可以帮我弄清楚我如何计算代码的长度,跨越多少行,新高度是什么以及如何更新DOM以反映这一点?
我在谷歌小组中找到了这个建议,但我真的不明白它在做什么以及如何调整高度.
editor.getSession().getDocument().getLength() *
editor.renderer.lineHeight + editor.renderer.scrollBar.getWidth()
Run Code Online (Sandbox Code Playgroud)
Hos*_*ork 86
(更新:我目前没有处理此问题,但我的回答可能已经过时.为了尝试合并其他人提供的内容,我将回应他们提到的minLines和maxLines属性,例如
editor.setOptions({
maxLines: Infinity
});
Run Code Online (Sandbox Code Playgroud)
显然无限是"不是一个好主意,因为即使对于非常大的文档,它也会禁用虚拟视口." 因此,选择限制可能会更好.
从历史的角度来看,旧答案是:
你引用的帖子只是假设它是一个固定宽度的字体,你知道它的字符高度,并且你知道文档中的行数.将它们相乘,您可以获得内容有多高的像素数.建议每次按下一个字符或剪切/粘贴(可能添加或删除行)时,您可以使用JavaScript将这个具体的新大小应用于DOM样式中的DOM项目.
(他们把滚动条的"宽度"扔进高度计算中,老实说,我不能告诉你背后是否存在理由.我会让其他人知道那部分.)
无论如何......如果你有软包装,跨越的渲染屏幕行数可能超过文档中"实际"行的数量.所以最好使用editor.getSession().getScreenLength()比editor.getSession().getDocument().getLength().
我将编辑器(位置:绝对)放在一个部分(位置:相对)中,它是生活在该部分中的唯一项目.这段代码现在似乎对我有用,如果我了解更多,我会更新它!
$(document).ready(function(){
var heightUpdateFunction = function() {
// http://stackoverflow.com/questions/11584061/
var newHeight =
editor.getSession().getScreenLength()
* editor.renderer.lineHeight
+ editor.renderer.scrollBar.getWidth();
$('#editor').height(newHeight.toString() + "px");
$('#editor-section').height(newHeight.toString() + "px");
// This call is required for the editor to fix all of
// its inner structure for adapting to a change in size
editor.resize();
};
// Set initial size to match initial content
heightUpdateFunction();
// Whenever a change happens inside the ACE editor, update
// the size again
editor.getSession().on('change', heightUpdateFunction);
}
Run Code Online (Sandbox Code Playgroud)
Dic*_*lth 33
Ace提供了一个选项:maxLines这样您就可以尝试:
editor.setOptions({
maxLines: 15
});
Run Code Online (Sandbox Code Playgroud)
http://jsfiddle.net/cirosantilli/9xdkszbz/
Car*_*ith 13
更新:见Dickeylth的回答.这一切仍然有效(人们似乎仍然觉得它很有用),但现在基本功能内置于ACE中.
要"在Ace Cloud9编辑器中自动调整内容的高度",只需编辑内容,只需调整编辑器的大小以适合包含它的div.假设你开始<div id=editor>......
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();
});
Run Code Online (Sandbox Code Playgroud)
您调整编辑器所在的div的大小,然后调用editor.resize以使编辑器重新填充div.
如果使用长行粘贴内容,并将ACE设置为换行,则新行和实际渲染行的数量将不同,因此编辑器将滚动.此代码将修复此问题,但您将获得水平滚动.
editor.getSession().setUseWrapMode(false)
Run Code Online (Sandbox Code Playgroud)
我认为解决方案可能是计算编辑器中的行数,然后调整它以适应这些行:
editor.setOptions({
maxLines: editor.session.getLength()
});
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助.