vue中光标自动显示到指定的input框内
1、给input加上ref;
1 <v-otp-input 2 ref="inputName" 3 class="opt-input" 4 length="9" 5 type="number" 6 pattern="\d*" 7 v-model="payNum" 8 plain 9 ></v-otp-input>
2、一进来就执行放在mounted里;
1 mounted(){ 2 this.$nextTick(() => { 3 this.$refs.inputName.focus(); 4 }) 5 },
3、如果想在执行事件之后让光标显示到input框内就加在事件中
1 testFun() { 2 this.$nextTick(() => { 3 this.$refs.inputName.focus(); 4 }) 5 }
4、另一种定位到头部的定法
this.$nextTick(() => { // this.$refs.inputName.focus(); const inputElement = this.$refs.inputName.$el.querySelector('input'); // 设置光标位置 inputElement.setSelectionRange(this.cursorPosition, this.cursorPosition); // 聚焦输入框 inputElement.focus(); })
5、同第4种一样,只不过定位到尾部
this.$nextTick(() => { const inputElement=this.$refs.inputName.$el.querySelector('input'); const length = inputElement.value.length; if (inputElement) { inputElement.setSelectionRange(length, length); inputElement.focus(); } })
参考文档
https://www.cnblogs.com/clark1990/p/16498108.html
浙公网安备 33010602011771号