是否可以将textarea作为ACE编辑器?

时间:2014-04-30 00:38:37

标签: javascript textarea ace-editor

我看到了类似的主题here,但我找不到答案。我正在尝试将Ace编辑器连接到textarea,但未成功。然后我发现“ ace works only on divs 。”

我更喜欢将编辑器连接到textarea,而不是div。那么,是否可以将Ace连接到textarea?

提前致谢!

1 个答案:

答案 0 :(得分:1)

这取决于你在更换后要用textarea做什么,但很容易用几行js

// create new ace instance
var editor = ace.edit(document.createElement("div"))
editor.session.setValue(textArea.value)
// set size
editor.container.style.height = textArea.clientHeight + "px";
editor.container.style.width = textArea.clientWidth + "px";
// replace textarea with the editor
textArea.parentNode.replaceChild(editor.container, textArea)
// trigger redraw of the editor
editor.resize()

并用textarea替换编辑器

var value = editor.getValue()
var start = editor.session.doc.positionToIndex(editor.selection.getRange().start)
var end   = editor.session.doc.positionToIndex(editor.selection.getRange().end)
textArea.value = value
textArea.setSelectionRange(start, end)
editor.container.parentNode.replaceChild(textArea, editor.container)
editor.destroy()

您也可以尝试使用ace https://github.com/ajaxorg/ace/blob/master/lib/ace/ext/textarea.js

中的textarea扩展名