Javascript字符串對象有一個toLocaleUpperCase()
函數,它使轉換本身變得簡單。
活資本Here's an example:
$(function() {
$('input').keyup(function() {
this.value = this.value.toLocaleUpperCase();
});
});
不幸的是,這完全復位的文本框的內容,因此用戶的插入位置(如果不是「文本框的終結」)丟失。
您可以hack this back in,不過,一些瀏覽器的切換法寶:
// Thanks http://blog.vishalon.net/index.php/javascript-getting-and-setting-caret-position-in-textarea/
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();
}
}
// The real work
$(function() {
$('input').keyup(function() {
// Remember original caret position
var caretPosition = getCaretPosition(this);
// Uppercase-ize contents
this.value = this.value.toLocaleUpperCase();
// Reset caret position
// (we ignore selection length, as typing deselects anyway)
setCaretPosition(this, caretPosition);
});
});
最終,這可能是最簡單的假貨。設置樣式text-transform: uppercase
的文本框,使其出現大寫給用戶,然後在你的JavaScript應用文本轉換一次,每當用戶插入符焦點離開文本框完全:
HTML:
<input type="text" name="keywords" class="uppercase" />
CSS:
input.uppercase { text-transform: uppercase; }
的Javascript:
$(function() {
$('input').focusout(function() {
// Uppercase-ize contents
this.value = this.value.toLocaleUpperCase();
});
});
希望這會有所幫助。
我希望我有時間把我所相信的是這裏最好的答案。這是爲了處理按鍵事件,並在適用的情況下將鍵碼更改爲大寫字母,它比聽起來更容易使跨瀏覽器兼容,但我認爲這是最好的解決方案。 – 2011-04-22 16:17:02
其實我想的解決方案只適用於IE ... e.which是隻讀的FF和WebKit,但IE可以讓你改變e.keyCode。在IE中試試這個http://jsfiddle.net/48fSq/1/ – 2011-04-22 21:57:12