目录

RichEditor实现上下角标数字的效果

问题现象

如何在RichEditor组件中实现上下角标的输入?

效果预览

背景知识

解决方案

  1. 创建RichEditor组件与RichEditorController控制器,在该组件的onReady回调方法中,调用控制器的addTextSpan方法,在该方法的第一个参数中输入文本值,在第二个参数设置style中fontFeature属性为subs,用于实现数字的下角标效果。
  2. 设置上角标同理,只需在第二个参数中设置fontFeature属性为sups即可。

完整示例参考如下:

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

  build() {
    Row() {
      Column() {
        RichEditor(this.options)
          .onReady(() => { // 组件初始化完成后会触发onReady回调
            // 在addTextSpan第一个参数中输入文本值,在第二个参数添加style,style中fontFeature属性为subs
            this.controller.addTextSpan('下角标效果示例:二氧化碳,CO2\n',
              {
                style:
                {
                  fontSize: 20,
                  fontFeature: '\"subs\"'
                }
              });
            this.controller.addTextSpan('上角标效果示例:X的平方,X2\n',
              {
                style:
                {
                  fontSize: 20,
                  fontFeature: '\"sups\"'
                }
              });
          })
          .borderWidth(1)
          .padding(5)
          .width('100%')
      }
      .width('100%')
    }
  }
}