出現(xiàn)focus無效原因:
ios的UIWebView 默認(rèn)的KeyboardDisplayRequiresUserAction為false,設(shè)置為true就行,WKWebView 不支持這個屬性,如果要從原生入手解決,請參考https://stackoverflow.com/questions/32407185/wkwebview-cant-open-keyboard-for-input-field
解決思路:
從無效原因可以看出,是鍵盤需要用戶觸發(fā)才能彈出,這導(dǎo)致了autofocus或者element.focus()無效,所以,在鍵盤彈出的情況下再去focus,或者跳轉(zhuǎn)到帶有autofocus的頁面也就可以正常focus了
解決方法:
通常的場景是,我們點擊頁面某個元素 => 邏輯交互 => 希望focus元素、或者跳轉(zhuǎn)到有aotufocus的頁面。再這里有個大前提,就是要有點擊頁面行為。
第一步:在點擊頁面時候,給一個占位的input進行focus,調(diào)起鍵盤;
第二步:邏輯交互、異步操作、settimeout延時處理等,在處理完成再focus到目標(biāo)input,或者跳轉(zhuǎn)到autofocus的頁面,就可以正常focus了。
劃重點
只要是點擊事件的回調(diào)就具備focus到input的能力,所以無論是點擊生成input再focus到這個input、還是跳轉(zhuǎn)到autofocus的頁面,先利用點擊focus到一個占位input調(diào)起鍵盤,在鍵盤存在的情況下調(diào)用element.focus()或者跳轉(zhuǎn)到有autofocus的頁面就都可以正常focus了。
占位input:
.clip{
position: absolute;
clip: rect(0 0 0 0);
}
<input ref="tempFocus" class="clip">
<div @click="gotoCommentClick">快來留言吧!</div>
gotoCommentClick() {
this.afterLogin().then(_ => {
this.$refs.tempFocus.focus();
this.$router.push(this.$route.path + '/comment');
})
},
comment.vue
mounted() {
this.$refs.editor.focus();
}
UC瀏覽器上注意事項:
uc瀏覽器,如果吊起鍵盤focus的input和延時再去focus的input不是同一個input,則第二個input無法正常focus,會出現(xiàn)鍵盤彈起又收起。處理方式是第二focus的input由第一個input復(fù)制插入到頁面就可以正常了。