移動端開發input標籤呼叫數字鍵盤
阿新 • • 發佈:2019-01-25
先上程式碼:
<input id="pp" type="number" maxlength="6" pattern="[0-9]*" name="password" oninput="if(value.length>6)value=value.slice(0,6)"/>
maxlength屬性規定輸入內容的最大長度,有些瀏覽器會出現把type設定為number後maxlength就失效了,微信瀏覽器我測試的時候還沒有遇到這種情況,為了預防萬一我們可以加上以下這行程式碼:
oninput="if(value.length>6)value=value.slice(0,6)" /*存在瀏覽器差異*/
type="text"和type=“number”親測在微信瀏覽器ios端中能調出數字鍵盤,但在安卓端中type="text"對某些手機自帶輸入法無效。
在開發過程中我遇到最棘手的問題不是如何呼叫手機數字鍵盤,而是如果要把當前這個input用作密碼用途的話如何將輸入的內容變成“·”,最後,我選擇通過改變input的type屬性來實現效果,通過oninput 事件觸發,當input中有新內容輸入時,觸發一次,程式碼如下:
但是如果我們在完成一次輸入後,重新點選input時呼叫的卻不是純數字鍵盤,因為此時我們的input屬性已經變成了password,但是如果我們在上面的程式碼前加上一個對input的focus觸發事件,將input的屬性重新修改成number可不可以呢?經過自己的幾次實踐,發現還是不能調用出純數字鍵盤,原因是當input標籤屬性已經為password時無論是focus事件或者是onclick事件觸發時,就會呼叫手機的鍵盤,此時input的屬性還是password。document.getElementById("pp").oninput=function(){ document.getElementById("pp").setAttribute("type", "password"); };
解決方法:
用一個div通過絕對定位或者相對定位遮蓋input(微信瀏覽器如果用float浮動的話容易發生點選穿透事件,即:點選表層會觸發底層的點選事件),相當於給input輸入框上面添加了一層罩。通過這個“罩”的點選來觸發改變input屬性的事件,完整程式碼如下:
<div id="pay" class="show" style="width:100%;height:100%; ">
<div class="nav" >
<span class="nav_s1" > 返回</span>
</div>
<div class="pay_header" >*請輸入密碼</div>
<div class="pay_pass" >
<input id="pp" type="number" maxlength="6" pattern="[0-9]*" name="password" oninput="if(value.length>6)value=value.slice(0,6)"/>
</div>
<div id="ppt" style="height:2.5rem;line-height: 2.5rem;width:100%;margin:0 auto;margin-top:-2.5rem;position: absolute" ></div>
<div class="pay_tip" >
忘記密碼?
</div>
<div id="pay_sure">
確定
</div>
<script>
document.getElementById("ppt").onclick=function() {
document.getElementById("pp").value="";
document.getElementById("pp").setAttribute("type", "number");
document.getElementById("pp").focus();
document.getElementById("pp").oninput=function(){
document.getElementById("pp").setAttribute("type", "password");
};
};
document.getElementById("pp").onblur=function() {
document.getElementById("pp").setAttribute("type", "password");
}
</script>
</div>