最近在做vue项目 订单支付这一块,当用户选择余额支付并点击`支付的时候,弹出如下框(PS:这里是我实现之后的效果,输入框本来是移动到看不见的位置,测试的时候才会把输入框移回来。)
需求:当弹出如下效果之后,要让输入框自动获取焦点(光标在输入框中闪烁)。
image.png
核心代码如下
html中
<input
class="input_control"
v-model="inputVal"
type="number"
oninput="if(value.length>6)value=value.slice(0,6)"
ref="getFocus"
id="inputValId"
/>
js中
data() {
return {
inputVal: "",
timer: null,
}
},
methods: {
goToPay: function(param1, param2) {
this.$nextTick(function() {
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {// 100毫秒延迟解决第二次打开支付框,输入框不自动获取焦点的bug
this.$refs.getFocus.focus();// 等价 document.getElementById("inputValId").focus();
}, 100);
});
}
- 遇到的坑
问题1.关闭遮罩,input失去焦点。再次点击支付按钮,输入框的焦点获取不到
解决办法:在$nextTick
设置100毫秒延迟,让this.$refs.getFocus.focus();
延迟100毫秒执行
if (this.timer) {
clearTimeout(this.timer);
}
this.timer = setTimeout(() => {
this.$refs.getFocus.focus();// 等价 document.getElementById("inputValId").focus();
}, 100);