用于大写文本输入的JavaScript代码

前端之家收集整理的这篇文章主要介绍了用于大写文本输入的JavaScript代码前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我正在使用流行的Firefox扩展Greasemonkey.

我想知道是否有办法以某种形式大写所有文本输入,所以如果我使用jQuery代码看起来像:

  1. $('form#formid input[type=text]').capitalize();

当然我知道.capitalize()不是一个有效的函数,为了大写文本你需要一个复杂的JavaScript代码,但毕竟谷歌搜索,我找不到一个似乎可以实现到Greasemonkey .

任何人都可以帮我写这个脚本吗?

通过大写,我的意思是大写每个单词的第一个字母,如CSS text-transform:capitalize;并且它必须覆盖用户可能放入的字母,也许在表单提交上更容易…

谢谢.

解决方法

  1. //add a function to jQuery so we can call it on our jQuery collections
  2. $.fn.capitalize = function () {
  3.  
  4. //iterate through each of the elements passed in,`$.each()` is faster than `.each()
  5. $.each(this,function () {
  6.  
  7. //split the value of this input by the spaces
  8. var split = this.value.split(' ');
  9.  
  10. //iterate through each of the "words" and capitalize them
  11. for (var i = 0,len = split.length; i < len; i++) {
  12. split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1);
  13. }
  14.  
  15. //re-join the string and set the value of the element
  16. this.value = split.join(' ');
  17. });
  18. return this;
  19. };

这是一个演示:http://jsfiddle.net/jasper/qppGQ/1/

这可以在事件处理程序中使用,以始终保持大写的文本体:

  1. //when the user presses a key and the value of the `textarea` is changed,the new value will have all capitalized words
  2. $('textarea').on('keyup',function () {
  3. $(this).capitalize();
  4. }).capitalize();//also capitalize the `textarea` element(s) on initialization

这是一个演示:http://jsfiddle.net/jasper/qppGQ/2/

更新

要使第一个字母大写,并且单词的其余部分为小写,我们可以在大写第一个字母后在字符串的其余部分中使用.toLowerCase():

  1. ...
  2. for (var i = 0,len = split.length; i < len; i++) {
  3. split[i] = split[i].charAt(0).toUpperCase() + split[i].slice(1).toLowerCase();
  4. }
  5. ...

这是一个演示:http://jsfiddle.net/jasper/qppGQ/3/

猜你在找的JavaScript相关文章