iOS下调用元素的focus方法,input元素不聚焦,键盘不弹起的问题

页面元素

<input type="text" ref="elInput"/>
 

<div
style="margin-top:20px;"
@click="confession()"
ref="elBtn">点击使input聚焦
</div>

js代码

methods(){
confession(){
this.$refs.elInput.focus()//显示键盘
}
}

上述代码在是有效的,但是对于input元素不是一直存在页面上,是动态显示的,上述方法就会失效

页面元素

<input v-show="isShow" type="text" ref="elInput"/>
<div
style="margin-top:20px;"
@click="confession()"
ref="elBtn">点击使input聚焦
</div>

js代码

data() {
return {
isShow:false
}
},
 

methods(){
confession(){
this.isShow=true
this.$nextTick(function(){
this.$refs.elInput.focus()//显示键盘
})
}
}

上述情况,ios下input聚焦是失效的,可以使用下面的方法(让input一直都在页面中)
将input写在页面上,利用定位给input显示在用户看不到的地方,当用户点击按钮时,将input定位到指定位置,显示出来
也可以将input透明度设为0,当用户点击按钮时,将input的透明对设为1

页面元素

<input :class="{'is-show':isShow}" type="text" ref="elInput"/>
<div
style="margin-top:20px;"
@click="confession()"
ref="elBtn">点击使input聚焦
</div>

js代码

data() {
return {
isShow:false,
}
},
 

methods(){
confession(){
this.isShow=true
this.$refs.elInput.focus()//显示键盘
}
}
 

<style lang="less" scoped>
input{
position:relative;
left:-1000px;
}
.is-show{
left:0;
}
</style>

上面的方法验证成功,注意,confession方法里面的 this.$refs.elInput.focus()这句代码不能放在异步或函数里面,否则也会失效

原因在于ios有所限制:
寻常代码里的focus不会生效,除了在某个UI事件(例如click, touchend等)的直接执行环境中调用focus

注意这个直接环境,它的意思是如果你在setTimeout, promise等异步方式中执行了focus,依然是无效的。

ios上述限制是出于安全机制的考虑

ios上只有用户交互触发的focus事件才会起效,而延时回调的focus是不会触发的

转载于:https://www.cnblogs.com/zhyzhy/p/10222496.html

  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值