失去焦点后在editor.js上检索块和光标位置

问题描述

我需要有关editor.js的帮助

想象一下以下情况,在我的页面上,我在右侧有editor.js,在屏幕右侧有许多按钮。

按钮是短语的集合,单击时,必须将短语插入到editor.js中。

但是,必须将其插入光标之前失去焦点的位置,考虑到它在editor.js中的任何位置,例如,可以在第一个,第二个或最后一个块中,并且在特定块中,光标可以在句子的开头,中间或结尾。

如何检索块和光标位置以插入新短语?

预先感谢

解决方法

您可以尝试使用以下方法将光标设置回上一个位置。但是,如果您在代码块中嵌套了元素,则无法正常工作。

editor.caret.setToBlock(/* current block index */,null,/* last cursor position */)

获取上一个光标位置:

let selection = document.getSelection();
let cursorPosition = selection.anchorOffset;

要获取当前块索引:

let currentBlockIndex = editor.blocks.getCurrentBlockIndex()

编辑器是您创建的editor.js实例。

参考:https://editorjs.io/caret#settoblock

,

我需要一个类似的功能,所以我使用 reactjs 做了以下操作来实现它。

创建的 ref 将保存当前索引 const currentBlockIndexRef = useRef('')

如何获取当前索引。

获取当前索引,使用api。当您单击用户想要添加内容的编辑器时,可以使用 Onchange(api),它将包含与用户想要添加内容的位置对应的当前块索引。如下图。

 const editor = new EditorJS({
     holder: editorId,logLevel: "ERROR",data: initData,onReady: () => {
       ejInstance.current = editor;
     },onChange: function(api,block) {
           console.log('api',api.blocks.getCurrentBlockIndex())
           currentBlockIndexRef.current= api.blocks.getCurrentBlockIndex() // update ref with the current index
         editor.save().then((data) => {
 
          setEditorData({ ...editorData,data,});
         })
       
     },autofocus: true,readOnly: false,tools: editorTools
   });
   editorJs = editor
 };
``` 

Then you can insert the block at the index 

 editorJs.blocks.insert('image',{...data.data},'',currentBlockIndexRef.current) // update the block