赞
踩
关于el-input获取焦点失去焦点时光标位置可以使用@focus方法;
随便写个el-input,设置ref、focus、blur属性和方法。
- <el-input
- ref="inputRef"
- v-model="testFocus"
- placeholder="请输入..."
- @focus="getCursor"
- @blur="inputBlur"
- >
- <template slot="prepend">前缀文字</template>
- <template slot="append">后缀文字</template>
- </el-input>
获取焦点时设置光标范围(2, 4)
HTMLInputElement.setSelectionRange
方法用于设定<input> 或 <textarea> 元素中当前选中文本的起始和结束位置。
属性 | 含义 |
selectionStart | 起始位置 |
selectionEnd | 结束位置 |
selectionDirection | forward、backward、none,三种选择方向,默认为forward从前向后 |
- methods: {
- inputBlur() {
- // 失去焦点是输出光标所在位置
- const textCursorStart = this.$refs.inputRef.$el.children[0].selectionStart;
- const textCursorEnd = this.$refs.inputRef.$el.children[0].selectionEnd;
- console.log(textCursorStart, textCursorEnd)
- },
- getCursor(event) {
- console.log(event)
- // 把光标移动input默认值的最后
- // event.target.setSelectionRange(this.position.length, this.position.length)
- // 设置光标范围(起始位置,结束位置,)
- event.target.setSelectionRange(2, 4)
- }
- }
setSelectionRange设置的光标范围是(2, 4)是生效的,但鼠标如果点击了input其他位置会覆盖这个设置,例如点击最后的位置,会使(2, 4)变成了(2, 9)
当我从下一个input,按键盘shift+tab反选这个input的时候,就发现选中(2, 4)了
所以这种方法仅在鼠标不点击input的时候好用,如果大佬能解决这个问题,记得回复我一下,感谢!
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。