Element UI Input组件内容格式化:换行时行首添加圆点

<el-input v-model="input"
          placeholder="请输入"
          type="textarea"
          :rows="8"
          @focus="handleFocus"
          @input.native="handleInput" />

解释一下:

  1. Element UI对 input 事件做了一层包装,无法返回event对象,使用 .native 修饰符可以返回event对象
  2. 圆点符号• 在Element UI默认的字体下显示为方块,需要修改默认字体为雅黑

<script>
export default {
  name: 'DashBoard',

  data () {
    return {
      input: ''
    }
  },

  methods: {
    // 获得焦点时,如果内容为空,首行添加圆点
    handleFocus () {
      if (this.input !== '') return
      this.input = '• '

    },
    
    // 录入文本时,每换一行在行首添加圆点
    handleInput (event) {
      if (event.inputType === 'insertLineBreak') {
        let txt = event.target
        let currentCursorPosition = txt.selectionStart
        let textBeforeCursor = txt.value.substring(0, currentCursorPosition)
        let textAfterCursor = txt.value.substring(currentCursorPosition)
        // 添加特殊符号到新行的行首
        txt.value = textBeforeCursor + "• " + textAfterCursor
        // 重新设置光标位置
        txt.setSelectionRange(currentCursorPosition + 2, currentCursorPosition + 2)
        // 双向绑定的数据重新赋值
        this.input = txt.value

      }
    }

  }
}
</script>

解释一下:

  • HTMLInputElement.selectionStart

         一个表示选择文本的开始索引的数字。当没有选择时,它返回当前文本输入光标位置的偏移量。

HTMLInputElement - Web API 接口参考 | MDN

 

  • InputEvent.inputType

         InputEvent 接口中的只读属性 inputType 返回对可编辑内容所做更改的类型。可能的更改包括插入、删除和格式化文本。以下是一些可能的 inputType 值:

  1. "insertText": 表示插入文本,通常与用户键入文本时触发的输入事件相关。
  2. "insertLineBreak": 表示插入换行符,通常与用户按下回车键时触发的输入事件相关。
  3. "deleteContentBackward": 表示向后删除内容,通常与用户按下删除键时触发的输入事件相关。
  4. "deleteContentForward": 表示向前删除内容,通常与用户按下删除键时触发的输入事件相关。
  5. "deleteWordBackward": 表示向后删除单词,通常与用户按下组合键(例如 Ctrl + Backspace)时触发的输入事件相关。
  6. "deleteWordForward": 表示向前删除单词,通常与用户按下组合键(例如 Ctrl + Delete)时触发的输入事件相关。

InputEvent.inputType - Web API 接口参考 | MDN

  • HTMLInputElement.setSelectionRange()

        HTMLInputElement.setSelectionRange 方法用于设定<input> 或 <textarea> 元素中当前选中文本的起始和结束位置。

HTMLInputElement.setSelectionRange() - Web API 接口参考 | MDN

最近更新

  1. TCP协议是安全的吗?

    2024-01-22 04:08:01       19 阅读
  2. 阿里云服务器执行yum,一直下载docker-ce-stable失败

    2024-01-22 04:08:01       19 阅读
  3. 【Python教程】压缩PDF文件大小

    2024-01-22 04:08:01       19 阅读
  4. 通过文章id递归查询所有评论(xml)

    2024-01-22 04:08:01       20 阅读

热门阅读

  1. 【力扣每日一题】力扣2788用分隔符拆分字符串

    2024-01-22 04:08:01       37 阅读
  2. Linux之firewall最常用命令

    2024-01-22 04:08:01       31 阅读
  3. 安卓之APK瘦身与资源压缩方案

    2024-01-22 04:08:01       31 阅读
  4. 【AI】深度学习在编码中的应用(8)

    2024-01-22 04:08:01       33 阅读
  5. 自动装箱与拆箱了解吗?原理是什么?

    2024-01-22 04:08:01       34 阅读
  6. 【C++】结构体

    2024-01-22 04:08:01       30 阅读
  7. JUC并发编程与源码分析学习笔记(二)

    2024-01-22 04:08:01       37 阅读
  8. Vue2:使用pubsub-js实现组件间通信

    2024-01-22 04:08:01       35 阅读