即時監聽移動端輸入框的變化

來源:互聯網
上載者:User

標籤: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();      });    })

  

 

即時監聽移動端輸入框的變化

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.