安卓和ios鍵盤擋住輸入內容

蔚藍的夢發表於2018-08-03
<script>
let iosUser = window.navigator.userAgent.indexOf(`iPhone`)
let inp = document.querySelector(`#inp`);//input輸入框
if (iosUser != -1) {
var bfscrolltop = document.body.scrollTop;//獲取軟鍵盤喚起前瀏覽器滾動部分的高度
inp.focus(function () {//在這裡‘input.inputframe’是我的底部輸入欄的輸入框,當它獲取焦點時觸發事件
interval = setInterval(function () {//設定一個計時器,時間設定與軟鍵盤彈出所需時間相近
document.body.scrollTop = document.body.scrollHeight;//獲取焦點後將瀏覽器內所有內容高度賦給瀏覽器滾動部分高度
}, 100)
}).blur(function () {//設定輸入框失去焦點時的事件
clearInterval(interval);//清除計時器
document.body.scrollTop = bfscrolltop;//將軟鍵盤喚起前的瀏覽器滾動部分高度重新賦給改變後的高度
});
} else {
inp.onclick = function (ev) {
document.querySelector(`body`).style.height = `999px`;
inp.style.position = `static`;
setTimeout(function () {
document.body.scrollTop = document.documentElement.scrollTop = inp.getBoundingClientRect().top + pageYOffset - 300;
}, 50);
window.addEventListener(`touchmove`, fn, false);
}

inp.onblur = function () {
document.querySelector(`body`).style.height = "auto"
document.querySelector(`body`).removeAttribute(`style`)
window.removeEventListener(`touchmove`, fn, false)
}

//觸控取消blur
function fn(ev) {
var _target = ev.target || ev.srcElement;
if (_target.nodeName != `INPUT`) {
inp.blur();
}
ev.preventDefault()
}
}
</script>

相關文章