vue3,光标所在位置插入字符,没有选中光标的话默认在输入框最前面添加字符...
时间: 2023-12-09 18:02:47 浏览: 41
你可以使用原生的 JavaScript 方法 `selectionStart` 和 `selectionEnd` 来获取光标的位置。然后在字符串中插入字符时,可以使用字符串的 `slice` 方法将字符串分为光标前的部分和光标后的部分,再将要插入的字符插入到中间,最后将两个部分拼接起来即可。
以下是一个简单的示例代码:
```html
<template>
<div>
<input type="text" ref="input" @input="onInput" />
</div>
</template>
<script>
export default {
methods: {
onInput(e) {
const input = this.$refs.input
const start = input.selectionStart
const end = input.selectionEnd
const value = input.value
const insertValue = 'x'
const newValue = value.slice(0, start) + insertValue + value.slice(end)
input.value = newValue
// 重置光标位置
input.selectionStart = input.selectionEnd = start + insertValue.length
},
},
}
</script>
```
在上面的示例中,`onInput` 方法中首先获取了光标的位置,然后将要插入的字符插入到输入框的值中,最后重置光标位置。需要注意的是,在重置光标位置时,需要将光标位置设置为插入字符后的位置,即 `start + insertValue.length`。