我决定打开一个新问题,因为我试图将单词的第一个字母大写为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"上运行函数时遇到了问题。我不能在输入中间编辑一些东西,而不让光标在输入的末尾。而且不能"select all"
我知道有解决方案来获得插入符号的位置和处理这样的事情,但我真的不知道如何将它们集成到我的代码中。
我该怎么做呢?
您可以从这里使用两个函数来完成此操作: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();
}
}
注意
您应该将这两个函数合并到您的大写函数范围