【问题标题】:retrieve block and cursor position on editor.js after lose focus在失去焦点后检索 editor.js 上的块和光标位置
【发布时间】:2021-01-21 23:20:36
【问题描述】:

我需要有关 editor.js 的帮助

想象以下场景,在我的页面上,editor.js 位于右侧,屏幕右侧有一堆按钮。

按钮是词组的集合,点击时必须将词组插入editor.js中

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

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

提前致谢

【问题讨论】:

    标签: editorjs


    【解决方案1】:

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

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

    获取最后一个光标位置:

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

    获取当前区块索引:

    let currentBlockIndex = editor.blocks.getCurrentBlockIndex()
    

    editor 是您创建的editor.js 实例。

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

    【讨论】:

    • 如果我的编辑器失去焦点它不起作用,getCurrentBlockIndex() 返回 -1
    • 您可以尝试使用focus()setToBlock(/* your previous index */) 函数,在调用getCurrentBlockIndex() 函数之前将焦点设置回您的编辑器。
    【解决方案2】:

    我需要一个类似的功能,所以我使用 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 
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-09-16
      • 2020-07-21
      • 1970-01-01
      • 1970-01-01
      • 2011-06-30
      • 1970-01-01
      • 2014-11-13
      相关资源
      最近更新 更多