目录

deleteSpans删除光标前一个内容

问题现象

使用deleteSpans方法,如何实现仅删除富文本光标前的一个内容?

背景知识

RichEditor是支持图文混排和文本交互式编辑的组件,其包含getCaretOffset方法用于获取光标位置。

解决方案

通过getCaretOffset方法获取光标位置,计算前一个内容的起始位置,并将其传入deleteSpans方法。

@Entry
@Component
struct RichEditorDeleteDemo {
  controller: RichEditorController = new RichEditorController();
  options: RichEditorOptions = { controller: this.controller };

  build() {
    Column() {
      Column() {
        RichEditor(this.options)
          .onReady(() => {
            this.controller.addTextSpan('点击delete,一次只删除一个内容');
          });
      }.width('100%');

      Button('delete').onClick(() => {
        let offset = this.controller.getCaretOffset();
        this.controller.deleteSpans({ start: offset - 1, end: offset });
      });
    }.height('100%');
  }
}