3

いくつかのキーワードを除いて、4文字以上の単語の最初の文字を大文字にしようとしていたため、新しい質問を開くことにしました。 /11/

$.fn.capitalize = function () {
 var wordsToIgnore = ["to", "and", "the", "it", "or", "that", "this"],
    minLength = 3;

  function getWords(str) {
    return str.match(/\S+\s*/g);
  }
  this.each(function () {
    var words = getWords(this.value);
    $.each(words, function (i, word) {
      // only continue if word is not in ignore list
      if (wordsToIgnore.indexOf($.trim(word).toLowerCase()) == -1 && $.trim(word).length > minLength) {
        words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
      }
    });
    this.value = words.join("");
  });
};

$('.title').on('keyup', function () {
  $(this).capitalize();
}).capitalize();

しかし、「keyup」で関数を実行しているときに問題が発生しました。入力の最後にカーソルを置かないと、入力の途中で何かを編集することはできません。また、「すべてを選択」することもできません。

キャレットの位置を取得してこのような処理を行うソリューションがあることは知っていますが、それらを自分のコードに統合する方法が本当にわかりません。

どうすればこれを行うことができますか?

4

1 に答える 1

4

ここから 2 つの関数を使用してこれを行うことができます: http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea

動作中の jsfiddle を参照してください: http://jsfiddle.net/Q2tFx/14/

$.fn.capitalize = function (e) {
  if(e.ctrlKey) return false;
  var wordsToIgnore = ["to", "and", "the", "it", "or", "that", "this"],
    minLength = 3;

  function getWords(str) {
    return str.match(/\S+\s*/g);
  }
  this.each(function () {
    var words = getWords(this.value);
    $.each(words, function (i, word) {
      // only continue if word is not in ignore list
      if (wordsToIgnore.indexOf($.trim(word).toLowerCase()) == -1 && $.trim(word).length > minLength) {
        words[i] = words[i].charAt(0).toUpperCase() + words[i].slice(1);
      }
    });
    var pos = getCaretPosition(this);
    this.value = words.join("");
    setCaretPosition(this, pos);
  });
};

$('.title').on('keyup', function (e) {
  var e = window.event || evt;
  if( e.keyCode == 17 || e.which == 17) return false;
  $(this).capitalize(e);
}).capitalize();


function getCaretPosition (ctrl) {
    var CaretPos = 0;   // IE Support
    if (document.selection) {
    ctrl.focus ();
        var Sel = document.selection.createRange ();
        Sel.moveStart ('character', -ctrl.value.length);
        CaretPos = Sel.text.length;
    }
    // Firefox support
    else if (ctrl.selectionStart || ctrl.selectionStart == '0')
        CaretPos = ctrl.selectionStart;
    return (CaretPos);
}
function setCaretPosition(ctrl, pos){
    if(ctrl.setSelectionRange)
    {
        ctrl.focus();
        ctrl.setSelectionRange(pos,pos);
    }
    else if (ctrl.createTextRange) {
        var range = ctrl.createTextRange();
        range.collapse(true);
        range.moveEnd('character', pos);
        range.moveStart('character', pos);
        range.select();
    }
}

ノート

この 2 つの関数を大文字化関数のスコープに組み込む必要があります

于 2013-01-10T17:10:16.090 に答える