1. 程式人生 > >移動端textarea輸入框監聽和輸入字數限制(相容ios和Android)

移動端textarea輸入框監聽和輸入字數限制(相容ios和Android)

image.png

html
<div class="textareaBox">
    <textarea class="wishContent" placeholder="請輸入不超過15個字" maxlength="15"></textarea>
    <span class="wordsNum">0/15</span>
</div>
css
.textareaBox {
   position: relative;
}

.wordsNum {
   position: absolute;
   bottom: 0.83
rem
; right: 0.83rem; color: #B3B3B3; font-size: 1rem; }
js

pc端監聽輸入框你可能想到focus、blur、hover、onkeyup這些事件
移動端有相容性問題,最佳方案是使用jq的 input propertychange監聽事件


//封裝一個限制字數方法
var checkStrLengths = function (str, maxLength) {
    var maxLength = maxLength;
    var result = 0;
    if (str && str.length > maxLength) {
        result = maxLength;
    } else
{ result = str.length; } return result; } //監聽輸入 $(".wishContent").on('input propertychange', function () { //獲取輸入內容 var userDesc = $(this).val(); //判斷字數 var len; if (userDesc) { len = checkStrLengths(userDesc, 15); } else { len = 0 } //顯示字數
$(".wordsNum").html(len + '/15'); });