我正在尝试设置一个只有一行文本的 Ace 编辑器。
这个想法是模仿 <input type="text">
的行为框,但带有语法着色:
所以我的问题是:
如何设置 Ace 只允许一行,就像标准文本输入框一样?
以下是我目前的尝试,以及未成功的原因。
调用
editor.undo()
在change
如果e.lines.length > 1
问题是,
change
在增量中应用实际更改之前被触发,因此undo()
在这里不起作用(或者它涉及以前的增量)正在取消
keypress
如果Event.which = 13
它有点用但很脏,而且它不处理粘贴多行文本的情况,所以我们需要处理
paste
事件也是如此 - 这将使这个解决方案更加肮脏。我也非常有信心会有更多的边缘情况需要考虑。试图“清空”
e
在on("change", function(e) { ... })
例如,说
e = {}
在回调函数中,前提是e
只是对实际对象的引用。没有任何影响。试图在 Ace 编辑器中找到一个内置参数来做到这一点
尚未成功找到这样的参数...
最佳答案
您可以使用以下代码使编辑器的行为类似于 input type="text"(主要取自 https://github.com/ajaxorg/ace/blob/v1.2.0/demo/kitchen-sink/layout.js#L103)
var el = document.getElementById("textbox")
var editor = ace.edit(el);
editor.setOptions({
maxLines: 1, // make it 1 line
autoScrollEditorIntoView: true,
highlightActiveLine: false,
printMargin: false,
showGutter: false,
mode: "ace/mode/javascript",
theme: "ace/theme/tomorrow_night_eighties"
});
// remove newlines in pasted text
editor.on("paste", function(e) {
e.text = e.text.replace(/[\r\n]+/g, " ");
});
// make mouse position clipping nicer
editor.renderer.screenToTextCoordinates = function(x, y) {
var pos = this.pixelToScreenCoordinates(x, y);
return this.session.screenToDocumentPosition(
Math.min(this.session.getScreenLength() - 1, Math.max(pos.row, 0)),
Math.max(pos.column, 0)
);
};
// disable Enter Shift-Enter keys
editor.commands.bindKey("Enter|Shift-Enter", "null")
#textbox {
font-size: 30px;
border:solid 2px gray;
}
body{
background: #161619;
padding: 40px 20px
}
<script src="https://ajaxorg.github.io/ace-builds/src/ace.js"></script>
<div id=textbox>var a = 1</div>
关于javascript - 单行 Ace 编辑器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32315244/