問題描述
iOS系統下,移動web頁面,inpu獲取焦點彈出系統虛擬鍵盤時,偶爾會出現擋住input的情況,盡管概率不大,但是十分影響用戶體驗。
問題重現
原始頁面:頁面中有header、main、footer三部分,其中 header 和 footer 通過 position: fixed; 定位在瀏覽器頂部和底部。
其中,footer 中有一個input 輸入框。

點擊 input 框使之獲取焦點,喚起虛擬鍵盤,正常頁面效果如下:

注:在ios系統喚起軟鍵盤,鍵盤和底部輸入框之間有一塊空白間距。
但是偶爾會出現軟鍵盤擋住input框的情況,如下:

針對此問題,目前沒有十分有效的方法,只能通過js調整input輸入框的位置,使之出現在正常的位置。
解決方法
scrollIntoView(alignWithTop): 滾動瀏覽器窗口或容器元素,以便在當前視窗的可見范圍看見當前元素。
再次測試,效果如下:

相比於input被擋住,突兀地出現在頁面中間更加可以令人接受,但是多次測試,仍然存在問題:當切換輸入法的時候,input框的位置會往下移動,被鍵盤擋住一部分,而且出現的概率比較高(中英文切換),效果如下:

針對這個問題,后期仍需要繼續調試和優化。
針對input輸入框被虛擬鍵盤擋住的問題,還有一個類似的解決方案:
當軟鍵盤被喚起是,使用 scrollTop() 方法使input元素滾動到指定的位置,但是滾動的具體數值需要調試才能給出,所以這里就不再演示了。
虛擬鍵盤擋住輸入框一直是web開發中的一個無法避免且令人頭疼的問題,希望有人能夠想出的更好的辦法,如果是瀏覽器或者系統的問題,希望官方可以盡快解決。
參考資料:
https://www.zhihu.com/question/32746176
http://www.tuicool.com/articles/j6zuIbn
http://blog.sina.com.cn/s/blog_637918a80101rsjh.html
Demo 完整代碼:
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <meta name="viewport" content="width=device-width,user-scalable=no,initial-scale=1.0,maximum-scale=1.0,minimum-scale=1.0">
5 <title><%= title %></title>
6 <link rel='stylesheet' href='/css/style.css' />
7 <script src="/js/jquery-3.1.1.min.js" charset="utf-8"></script>
8 <style>
9 html, body {
10 height: 100%;
11 padding: 0;
12 margin: 0;
13 }
14 header {
15 position: fixed;
16 top: 0;
17 left: 0;
18 z-index: 9999;
19 width: 100%;
20 height: 50px;
21 line-height: 50px;
22 font-size: 18px;
23 text-align: center;
24 background: #ccc;
25 }
26 main {
27 position: absolute;
28 top: 50px;
29 bottom: 10px;
30 left: 20px;
31 width: 100%;
32 margin-bottom: 50px;
33 /* 使之可以滾動 */
34 overflow-y: scroll;
35 /* 增加該屬性,可以增加彈性,是滑動更加順暢 */
36 -webkit-overflow-scrolling: touch;
37 }
38 footer {
39 position: absolute;
40 bottom: 0;
41 left: 0;
42 width: 100%;
43 height: 50px;
44 line-height: 50px;
45 text-align: center;
46 background: #666;
47 border-top: 1px solid #e6e6e6;
48 }
49 footer input {
50 display: inline-block;
51 width: 90%;
52 height: 20px;
53 font-size: 14px;
54 outline: none;
55 border: 1px solid #e6e6e6;
56 border-radius: 5px;
57 }
58 </style>
59 </head>
60 <body>
61 <header>
62 This is the header
63 </header>
64 <main>
65 <h1><%= title %></h1>
66 <p>Welcome to <%= title %></p>
67 <ul>
68 <li>Today</li>
69 <li>is</li>
70 <li>Sunday</li>
71 <li>And</li>
72 <li>I</li>
73 <li>have</li>
74 <li>to</li>
75 <li>go</li>
76 <li>to</li>
77 <li>work</li>
78 <li>tomorrow</li>
79 </ul>
80 </main>
81 <footer>
82 <input type="text" placeholder="Type here...">
83 </footer>
84 </body>
85 <script type="text/javascript">
86 $(function() {
87 $('input').on('click', function () {
88 var target = this;
89 // 使用定時器是為了讓輸入框上滑時更加自然
90 setTimeout(function(){
91 target.scrollIntoView(true);
92 },100);
93 });
94 })
95 </script>
96 </html>
