標籤:logs sea log 版本 即時 target asc 多個 javascrip
一個常見需求,即時監聽textarea的輸入變化,並在頁面上顯示還能夠輸入多少字元。
開發過程中翻了兩個形式錯誤:
1、僅僅使用onkeyup事件
2、使用zepto綁定事件的時候,經驗主義錯誤
第三方IME在輸入拼音的時候,並沒有把輸入的漢字直接寫在輸入框內,而是在IME上方暫存,只有選擇了字後才填到textarea輸入框中,這時候是兼聽不到鍵盤事件的,所以完全依賴keyup事件,是沒辦法準確擷取所輸入的字元數的,所以只能監聽其他事件,HTML5新增事件oninput完美解決這一bug,但是當我檢查其相容性時,http://caniuse.com/#search=oninput 給出的相容性列表是:
ios版本最低只相容到9.3, Android 4.4就有點悲催了。
但實際檢測,使用的是iPhone5s,版本為7.0的也能夠正確監聽到input事件。
第二個錯誤更是經驗主義錯誤,
$(function () { var wordCount = 0, totalCount = 20, remaining = totalCount - wordCount; $(‘#overage‘).text(remaining); $(‘textarea‘).on(‘input, focus, keyup‘, function (ev) { wordCount = $.trim($(this).val()).length; remaining = totalCount - wordCount; if (remaining <= 0) { $(this).val($(this).val().slice(0, totalCount)); $(‘#overage‘).text(0); } else { $(‘#overage‘).text(remaining); } ev.stopPropagation(); }); })
估計很多人會和我一樣,看不出來錯誤在哪裡?
事實上,zepto包括jquery使用on綁定多個事件,中間是以空格分開的,而不是逗號。
$(function () { var wordCount = 0, totalCount = 20, remaining = totalCount - wordCount; $(‘#overage‘).text(remaining); $(‘textarea‘).on(‘input focus keyup‘, function (ev) { wordCount = $.trim($(this).val()).length; remaining = totalCount - wordCount; if (remaining <= 0) { $(this).val($(this).val().slice(0, totalCount)); $(‘#overage‘).text(0); } else { $(‘#overage‘).text(remaining); } ev.stopPropagation(); }); })
即時監聽移動端輸入框的變化