頁面元素
<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是不會觸發的