在移動端的web開發中,一提起輸入框,程序猿(媛)確定有不少能夠吐槽的點。javascript
在輸入框的運用中,小編也是很心累呀~
不過,通過我 潛(cai)心(keng)研(jiao)究(xun),也算是瞭解了它的脾性… …css
特別鳴謝:周涵,家興等java
正文這裏開始 👇 — — — — — — — —ios
當頁input存在於吸頂或者吸底元素中時,用戶點擊輸入框,輸入法彈出後,fiexd失效,頁面中定位好的元素隨屏幕滾動。css3
針對這個問題,咱們一塊兒來看下如下幾種方案:web
方案一: Web API 接口 :scrollIntoView 的應用,將input輸入框顯示在可視區域。佈局
// 輸入框得到焦點時,元素移動到可視區域 inputOnFocus(e) { setTimeout(function(){ e.target.scrollIntoView(true); // true:元素的頂端將和其所在滾動區的可視區域的頂端對齊; false:底端對齊。 },200); // 延時 == 鍵盤彈起須要時間 }
一行代碼,輕鬆搞定,輸入框就乖乖的出如今你眼前了。ui
不過有點小缺陷:頁面過長時,因爲fixed失效,輸入框依然也會跟着頁面滑走。spa
這時,咱們須要一個固定的輸入框……code
方案二:在輸入框得到焦點時,將頁面滑動到最底部,避免fixed致使的頁面亂飛,而且保證input在最底部。
var timer; // 輸入框得到焦點時,將元素設置爲position:static,設置timer inputOnFocus(e) { e.target.style.className = 'input input-static'; timer = setInterval( function() { document.body.scrollTop = document.body.scrollHeight }, 100) }; // 輸入框失去焦點時,將元素設置爲 position:fixed,清除timer inputOnbulr(e) { e.target.parentNode.className = 'input input-fixed'; clearInterval(timer) };
效果以下圖
,
當得到焦點彈出虛擬鍵盤後,input輸入框會一直緊貼鍵盤頂部。若是,你的頁面彈出輸入法後不須要滑動查看其餘內容,那麼你對這種方案應該很中意。
But,可能你作的是一個相似聊天的頁面,須要在回覆時,查看歷史消息,那麼,請你繼續往下看
方案三:將頁面進行拆分: 頁面(main) = 內容(sectionA) + 輸入框(sectionB)+ 其餘(sectionOther)
原理 :
main.height = window.screen.height ;
sectionA 絕對定位,進行內部滾動 overflow-y:scroll ;
sectionB 可保證在頁面最底部。
.main { position: relative; height: 100%; } .sectionA { box-sizing: border-box; padding-bottom: 60px; height: 100%; overflow-y: scroll; -webkit-overflow-scrolling: touch //爲了使滾動流暢,sectionA 添加屬性 } .sectionB { position: absolute; height: 60px; overflow: hidden; left: 0; right: 0; bottom: 0; }
純css3打造,能夠滾動,能夠固定位置,基本知足大部分佈局須要。
這個是IOS的一個bug,能夠考慮用 textarea 替換 input,設置一行的高,進行上下滾動查看。(其餘方案能夠參看下面 第 6 點)
-webkit-user-select:none 致使 input 框在 IOS 中沒法輸入,光標不出現,設置以下
user-select:text; -webkit-user-select:text;
利用scrollIntoView 使當前元素出現到指定位置,避免光標錯位,設置以下:
e.target.scrollIntoView(true); e.target.scrollIntoViewIfNeeded();
onkeyPress(e) {
const testLength = e.target.value.length; e.target.style.width = `${testLength*8+10}px` }
這種方案基本知足自動獲取效果。
testLength 8 英文字符,testLength 16中文字符, +10爲後邊光標預留位置。
這種方案顯然不適用於對精確度有很高要求的需求。
(1)div設置contentditable=true 能夠將此元素變成可輸入狀態。
<div class="inputContent" contenteditable="true" ></div>
(2)想要變成input輸入框,利用css模擬輸入框的樣式
.inputContent{ color:#444; border:#999 solid 1px; border-radius: 3px; padding: 5px 10px; box-sizing: border-box; min-width:50px; max-width: 300px; background: #ffffff; }
這裏配合min-width,max-width 效果更真實。
(3)點擊div能夠彈出軟鍵盤,可是沒法輸入內容,須要設置屬性,以下
.inputContent{ user-select:text; -webkit-user-select:text; }
這樣就完成一個能夠根據獲取輸入內容來動態來調節寬高。
還能夠利用js模擬placeholder等,這裏就不展開了
輸入框得到焦點可彈出軟鍵盤,卻沒有光標閃爍,也沒法正常輸入。
-webkit-user-select:none 致使的,能夠這樣解決
*:not(input,textarea) { -webkit-touch-callout: none; -webkit-user-select: none; }
// 使用僞類 input::-webkit-input-placeholder, input::-moz-placeholder, input::-ms-input-placeholder { ...style text-align: center; }
做者:大轉轉FE/張穎
zzfe.org/#/detail/5a8e3e67e772cd17475c8c6b