我编写了一个普通 JavaScript 纯文本编辑器的小示例,但我无法将光标放在文本区域上并插入文本。我的问题是我可能需要做什么才能使这个示例允许使用光标插入文本。我想将光标放在 contenteditable div 上并开始输入以插入字符。
HTML
<h1>Hello, Lexical!</h1>
<div id="editor" contenteditable="true" style:"width: 100px"></div>
JS
// See https://www.npmjs.com/package/lexical documentation.
import * as lexical from 'https://esm.run/lexical';
import {registerPlainText} from 'https://cdn.jsdelivr.net/npm/@lexical/[email protected]/+esm'
const config = {
namespace: 'MyEditor',
editable: true,
};
const editor = lexical.createEditor(config);
const contentEditableElement = document.getElementById('editor');
editor.setRootElement(contentEditableElement);
registerPlainText(editor);
editor.setEditable(true);
我在这里添加了一个 JSFiddle ,如果有任何建议,我将不胜感激。
使用
contentEditable
已经使 div
元素可编辑。但是,您使用的词汇库会在现有 contentEditable
元素之上创建自己的编辑器实例,从而阻止交互。
简单使用:
<h1>Hello, Lexical!</h1>
<div id="editor" contentEditable="true" style="width:100px;border:1px solid black"></div>
<script>
const editor = document.getElementById('editor');
editor.focus(); // This should allow typing, without lexicon
</script>
有词典:
import { EditorState, EditorConfiguration, Plugin } from 'lexical';
import { PlainTextPlugin } from 'lexical-plain-text';
// Create the editor configuration
const editorConfig = new EditorConfiguration({
namespace: 'MyEditor',
editorState: new EditorState(),
plugins: [new PlainTextPlugin()],
});
const editor = editorConfig.createEditor();
// Get the DOM element, set root element, apply editor config
const contentEditableElement = document.getElementById('editor');
editor.setRootElement(contentEditableElement);
editor.applyConfiguration(editorConfig);
Render the editor
editor.updateEditor();
editor.setEditable(true);
您需要
lexical-plain-text
纯文本插件包。