一、需求:進入頁面自動聚焦輸入框,並彈出軟鍵盤
實測
1、通過js執行focus(),安卓下只聚焦,出現光標,不彈出軟鍵盤;IOS下連光標都未出現。
2、增加autofocus屬性,結果同上。
3、將代碼放入延遲函數setTimeout 中執行,結果同上。
4、通過button點擊執行focus(),文本框聚焦且彈出軟鍵盤
解決方案:
1、通過點擊屏幕的其他區域,然後觸發input的focus事件,喚起鍵盤:
進入頁面後,給頁面加一層遮罩層,點擊遮罩層時關閉該層並執行focus()。
2、重寫input輸入框及軟鍵盤
二、問題:當輸入信息時彈出軟鍵盤,因手機屏幕有限汪汪會遮住輸入框
解決方案:
scrollIntoViewIfNeeded:只在當前元素在視窗的可見範圍內不可見的情況下,才滾動瀏覽器窗口或容器元素,最終讓當前元素可見。
當虛擬鍵盤彈出的時候,window的resize事件會被觸發。
監聽input元素的focus事件,以及window的resize事件。因爲focus事件將在resize事件前觸發。然後通過scrollIntoViewIfNeeded使輸入框可見。
1、監聽input元素的focus事件
var inputs = document.getElementsByTagName("input"); for (var i = 0; i< inputs.length; i++) { inputs[i].onclick = function (e) { window.setTimeout(function () { e.target.scrollIntoViewIfNeeded(); }, 0); } }
2、監聽window的resize事件
if (/Android/gi.test(navigator.userAgent)) { window.addEventListener('resize', function () { if (document.activeElement.tagName == 'INPUT' || document.activeElement.tagName == 'TEXTAREA') { window.setTimeout(function () { document.activeElement.scrollIntoViewIfNeeded(); }, 0); } }) }