Making Caps to the first letter automatically
我想让文本框中的第一个字母大写,但我不知道如何应用它。例如西塔利梅拉---->西塔利梅拉
我想将此应用于文本框。
谢谢你的帮助。
请试试这个。它起作用了。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | <!DOCTYPE HTML PUBLIC"-//W3C//DTD HTML 4.01 Transitional//EN""http://www.w3.org/TR/html4/loose.dtd"> <html> <head> Capitalizing first letter in a textbox <script type="text/javascript"> function capitalize(textboxid, str) { // string with alteast one character if (str && str.length >= 1) { var firstChar = str.charAt(0); var remainingStr = str.slice(1); str = firstChar.toUpperCase() + remainingStr; } document.getElementById(textboxid).value = str; } <body> <form name="myform" method="post"> <input type="text" id="mytextbox" onkeyup="javascript:capitalize(this.id, this.value);"> </form> </body> </html> |
CSS
1 2 3 | input[type=text] { text-transform: capitalize; } |
这将使文本以这种方式显示。
演示:http://jsfiddle.net/gvee/csc8kk/
要在JavaScript中执行此操作,请获取节点,并用转换替换它的值。
1 2 3 | var textbox = document.getElementById('myTextboxId'); textbox.value = textbox.value.charAt(0).toUpperCase() + textbox.value.slice(1); |
多媒体数据页面
document.getElementById String.prototype.charAt String.prototype.toUpperCase String.prototype.slice
工作演示…
http://jsfiddle.net/billymon/mzxlc/1/
HTML1 | <input type="text" id="targetBox"> |
JavaScript
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | var capitalize = function(e){ // if the first letter is lowercase a-z // ** don't run the replace unless required, to permit selecting of text ** if(this.value.match(/^[a-z]/)){ // replace the first letter this.value = this.value.replace(/^./,function(letter){ // with the uppercase version return letter.toUpperCase(); }); } } // listen to key up in case of typeing, or pasting via keyboard // listen to mouseup in case of pasting via mouse // prefer `up` events as the action is complete at that point document.getElementById('targetBox').addEventListener('keyup', capitalize); document.getElementById('targetBox').addEventListener('mouseup', capitalize); |