uniapp textarea 如何获取光标所在行

在uniapp中,如何获取textarea组件中光标当前所在的行数?我尝试通过selectionStart属性获取光标位置,但不知道如何转换成对应的行号。有没有现成的API或计算方法可以实现这个功能?需要兼容H5和微信小程序平台。

2 回复

在uniapp中,可通过selectionchange事件获取光标位置,再结合textarea内容计算当前行数。示例:

onSelectionChange(e) {
  const text = e.detail.value
  const cursorPos = e.detail.cursor
  const lines = text.substr(0, cursorPos).split('\n')
  const currentLine = lines.length
}

在 UniApp 中,可以通过监听 textareakeyboardheightchange 事件并结合计算来获取光标所在行。以下是实现方法:

  1. textarea 组件上绑定 keyboardheightchange 事件,并获取输入内容。
  2. 使用 selectionchange 事件(部分平台支持)或通过计算光标位置来推断行数。

示例代码:

<template>
  <view>
    <textarea 
      v-model="inputText" 
      @keyboardheightchange="onKeyboardHeightChange"
      @selectionchange="onSelectionChange"
      placeholder="输入内容..."
    />
    <text>光标所在行:{{ currentLine }}</text>
  </view>
</template>

<script>
export default {
  data() {
    return {
      inputText: '',
      currentLine: 1
    };
  },
  methods: {
    onSelectionChange(e) {
      // 获取光标位置
      const cursorPos = e.detail.cursor;
      // 根据换行符计算行数
      const textBeforeCursor = this.inputText.substring(0, cursorPos);
      this.currentLine = textBeforeCursor.split('\n').length;
    },
    onKeyboardHeightChange(e) {
      // 可选:处理键盘高度变化
    }
  }
};
</script>

注意事项:

  • selectionchange 事件在部分平台(如微信小程序)可能不支持,建议测试目标平台兼容性。
  • 如果无法使用 selectionchange,可通过 textareafocusinput 事件结合计算光标位置,但实现较复杂。

此方法通过计算光标前的换行符数量来确定当前行,简单有效。

回到顶部