3

我决定提出一个新问题,因为我试图用 4 个或更多字母大写单词的第一个字母,除了几个关键词,我有这个工作代码:http: //jsfiddle.net/Q2tFx /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

你可以从这里使用两个函数来做到这一点: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();
    }
}

笔记

您应该将这两个函数合并到您的大写函数范围中

于 2013-01-10T17:10:16.090 回答