首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >在失去焦点后检索editor.js上的块和光标位置

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

Stack Overflow用户
提问于 2020-10-07 11:07:01
回答 2查看 574关注 0票数 0

我需要editor.js方面的帮助

想象一下下面的场景,在我的页面上,editor.js在右边,一堆按钮在屏幕的右边。

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

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

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

提前感谢

EN

回答 2

Stack Overflow用户

发布于 2020-10-08 19:36:43

您可以尝试使用下面的选项将光标设置回以前的位置。但是,如果块中有嵌套元素,这就不能正常工作。

代码语言:javascript
复制
editor.caret.setToBlock(/* current block index */, null, /* last cursor position */)

要获取最后一个光标位置,请执行以下操作:

代码语言:javascript
复制
let selection = document.getSelection();
let cursorPosition = selection.anchorOffset;

要获取当前块索引,请执行以下操作:

代码语言:javascript
复制
let currentBlockIndex = editor.blocks.getCurrentBlockIndex()

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

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

票数 1
EN

Stack Overflow用户

发布于 2021-08-01 10:00:46

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

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

如何获取当前索引。

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

代码语言:javascript
复制
 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
 };

然后,您可以在索引处插入块

代码语言:javascript
复制
```javascript

editorJs.blocks.insert('image',{...data.data},'',currentBlockIndexRef.current) //更新分块

代码语言:javascript
复制
```javascript
代码语言:javascript
复制
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64236633

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档