1、需求:進入頁面自動聚焦輸入框,並彈出軟鍵盤瀏覽器
實測ide
一、經過js執行focus(),安卓下只聚焦,出現光標,不彈出軟鍵盤;IOS下連光標都未出現。函數
二、增長autofocus屬性,結果同上。spa
三、將代碼放入延遲函數setTimeout 中執行,結果同上。orm
四、經過button點擊執行focus(),文本框聚焦且彈出軟鍵盤事件
解決方案:get
一、經過點擊屏幕的其餘區域,而後觸發input的focus事件,喚起鍵盤:input
進入頁面後,給頁面加一層遮罩層,點擊遮罩層時關閉該層並執行focus()。it
二、重寫input輸入框及軟鍵盤io
2、問題:當輸入信息時彈出軟鍵盤,因手機屏幕有限汪汪會遮住輸入框
解決方案:
scrollIntoViewIfNeeded:只在當前元素在視窗的可見範圍內不可見的狀況下,才滾動瀏覽器窗口或容器元素,最終讓當前元素可見。
當虛擬鍵盤彈出的時候,window的resize事件會被觸發。
監聽input元素的focus事件,以及window的resize事件。由於focus事件將在resize事件前觸發。而後經過scrollIntoViewIfNeeded使輸入框可見。
一、監聽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); } }
二、監聽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); } }) }