我有一个网站,我在其中使用 CodeMirror 编辑器输入数据。我想添加非常简单的自动完成功能:我有一些以 @ 符号开头的词(@cat、@dog、@bird 等),我希望编辑器在用户键入 @ 或 @c 时显示带有这些词的下拉列表 - 我该怎么做这?我看到了自动完成插件,但它们需要按 ctrl+space 并使用模式……所以,任何帮助都会很棒!
谢谢!
最佳答案
方法如下(假设您已经加载了 CodeMirror 和 show-hint
插件):
// Dummy mode that puts words into their own token
// (You probably have a mode already)
CodeMirror.defineMode("mylanguage", function() {
return {token: function(stream, state) {
if (stream.match(/[@\w+]/)) return "variable";
stream.next();
return null;
}};
});
// Register an array of completion words for this mode
CodeMirror.registerHelper("hintWords", "mylanguage",
["@cat", "@dog", "@bird"]);
// Create an editor
var editor = CodeMirror(document.body, {mode: "mylanguage"});
// When an @ is typed, activate completion
editor.on("inputRead", function(editor, change) {
if (change.text[0] == "@")
editor.showHint();
});
关于javascript - 预定义单词的 CodeMirror 编辑器自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28546664/