[英]Auto Capitalize ONLY the First Letter of Each Word in an Input Field
我有多个输入字段来获取城市。 我想在用户输入城市名称的同时将 每个单词的第一个字母自动大写,而其余字母则强制为小写 。
注意:由于我的要求,CSS text-transform
属性将不起作用,因为它只修改单词的第一个字母 - - 如果用户键入超出第一个字母的大写字母,则不会调整它。
到目前为止,我有这个JavaScript:
function forceLower(strInput) {
strInput.value=strInput.value.toLowerCase();
}
哪个成功将整个输入转换为小写。
有关详细信息,请参阅内联注释
// Get a reference to the input and wire it up to an input event handler that // calls the fixer function document.getElementById("txtTest").addEventListener("input", forceLower); // Event handling functions are automatically passed a reference to the // event that triggered them as the first argument (evt) function forceLower(evt) { // Get an array of all the words (in all lower case) var words = evt.target.value.toLowerCase().split(/\\s+/g); // Loop through the array and replace the first letter with a cap var newWords = words.map(function(element){ // As long as we're not dealing with an empty array element, return the first letter // of the word, converted to upper case and add the rest of the letters from this word. // Return the final word to a new array return element !== "" ? element[0].toUpperCase() + element.substr(1, element.length) : ""; }); // Replace the original value with the updated array of capitalized words. evt.target.value = newWords.join(" "); }
<input type="text" id="txtTest">
你可以使用css进行这个text-transform:capitalize
function firstCap(str){ var returnVar=''; var strSplit=str.split(' '); for(var i=0;i<strSplit.length;i++){ returnVar=returnVar+strSplit[i].substring(0,1).toUpperCase()+strSplit[i].substring(1).toLowerCase() +' '; } return returnVar }
div , input {text-transform: capitalize;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div> this is only the first lettter</div> <input type="text"/>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.