uniapp的editor编辑器里如何提取光标选中的文字

在uniapp的editor编辑器中,如何获取用户光标当前选中的文字内容?我尝试使用官方文档提供的方法,但始终无法正确提取选中文本,请问应该如何实现这个功能?

2 回复

在uniapp的editor组件中,可通过editorContext.getSelectionRange()获取选区信息,再结合editorContext.getContents()提取选中文字。


在 UniApp 的 editor 组件中,可以通过 editoronSelectionChange 事件监听光标选中状态,并使用 editorContext.getSelectionRangeeditorContext.getContents 方法提取选中的文字。

实现步骤:

  1. editor 组件上绑定 onSelectionChange 事件。
  2. 在事件回调中,通过 editorContext 获取选中范围。
  3. 根据选中范围,从编辑器内容中提取文字。

示例代码:

<template>
  <view>
    <editor id="myEditor" @selectionchange="onSelectionChange" />
    <button @click="getSelectedText">获取选中文字</button>
  </view>
</template>

<script>
export default {
  data() {
    return {
      editorCtx: null,
      selectionRange: null // 存储选中范围
    };
  },
  methods: {
    onEditorReady() {
      // 初始化 editorContext
      uni.createSelectorQuery()
        .select('#myEditor')
        .context((res) => {
          this.editorCtx = res.context;
        })
        .exec();
    },
    onSelectionChange(e) {
      // 监听选中变化,保存选中范围
      this.selectionRange = e.detail;
    },
    async getSelectedText() {
      if (!this.editorCtx || !this.selectionRange) {
        uni.showToast({ title: '未选中文字', icon: 'none' });
        return;
      }

      // 获取编辑器全部内容
      const { html } = await this.editorCtx.getContents();
      
      // 提取选中文字(简单示例,实际需根据 selectionRange 处理)
      const selectedText = this.extractTextFromHTML(html, this.selectionRange);
      console.log('选中文字:', selectedText);
      uni.showToast({ title: `选中: ${selectedText}`, icon: 'none' });
    },
    // 简化版提取逻辑(需根据实际需求完善)
    extractTextFromHTML(html, range) {
      // 此处需解析 HTML 并根据 range 计算选中文字
      // 建议使用第三方库(如 parse5)或自定义逻辑处理
      return '提取功能需自行实现';
    }
  },
  mounted() {
    this.onEditorReady();
  }
};
</script>

注意事项:

  • 选中范围处理selectionRange 提供的是相对位置信息,需结合编辑器内容(HTML)解析选中文字。
  • HTML 解析editor 内容为 HTML 格式,提取文字时需去除标签(可使用 textContent 或第三方库如 parse5)。
  • 平台差异:不同平台(微信小程序、H5 等)可能存在兼容性问题,建议测试目标平台。

如需完整实现,请参考 UniApp 官方文档 editor 组件

回到顶部