js解決軟鍵盤遮擋輸入框問題
阿新 • • 發佈:2019-01-24
經驗須知
- 彈出軟鍵盤時:
- ios端$(‘body’).scrollTop()會改變
- android端$(window).height()會改變
- 拉起鍵盤不是一瞬間,而是有一個緩動過程
問題重現
- ios端,經常會出現輸入法遮擋輸入框的問題(特別是那種有一個白色頂部的輸入法,如:百度輸入法),如圖:
-
問題解決
- 我們只需要在輸入框聚焦之後,開啟一個定時器,執行$(‘body’).scrollTop(1000000),這樣由於整個body滾動到了最下面,輸入框自然就看見了,具體請檢視以上示例
示例原始碼
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, minimum-scale=1, maximum-scale=1, user-scalable=no"> <meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1"/> <title>demo</title> <script src="../js/jquery-1.11.3.min.js"></script> <style> * { margin: 0; padding: 0; } body, html { width: 100%; height: 100%; } .bottom { position: absolute; left: 0; bottom: 0; width: 100%; font-size: 0; } input { font-size: 14px; box-sizing: border-box; width: 50%; height: 50px; line-height: 50px; } </style> </head> <body> <div class="bottom"> <input class="aInput" type="text" placeholder="ios聚焦後會被輸入法遮擋" /> <input class="bInput" type="text" placeholder="ios聚焦後不會被輸入法遮擋" /> </div> </body> <script> $(function() { // 解決輸入法遮擋 var timer = null; $('.bInput').on('focus', function() { clearInterval(timer); var index = 0; timer = setInterval(function() { if(index>5) { $('body').scrollTop(1000000); clearInterval(timer); } index++; }, 50) }) }); </script> </html>