3

HTML に属性があることは知っていますが、文字ではなく入力する単語maxlengthの数を制限したいと考えています。

10 単語の後、ユーザーはカーソルを左に移動してテキストを編集できますが、それ以上単語を追加することはできません。

では、どうすればカーソルを停止できますか?

助言がありますか?

JavaScriptのみでお願いします。

4

5 に答える 5

0

@sgrovesのように、この答えはただの楽しみです:)

$(document).ready(function(){

  $('textarea').on('keydown', function(e){
    // ignore backspaces
    if(e.keyCode == 8)
      return;

    var that = $(this);
    // we only need to check total words on spacebar (i.e the end of a word)
    if(e.keyCode == 32){
      setTimeout(function(){ // timeout so we get textarea value on keydown
        var string = that.val();
        // remove multiple spaces and trailing space
        string = string.replace(/ +(?= )| $/g,'');
        var words = string.split(' ');
        if(words.length == 10){
          that.val(words.join(' '));
        }
      }, 1);
    }
  });
});
于 2013-06-05T22:07:26.087 に答える