微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

我正在使用流行的Firefox扩展Greasemonkey.

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

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

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

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

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

谢谢.

解决方法

//add a function to jQuery so we can call it on our jQuery collections
$.fn.capitalize = function () {

    //iterate through each of the elements passed in,`$.each()` is faster than `.each()
    $.each(this,function () {

        //split the value of this input by the spaces
        var split = this.value.split(' ');

        //iterate through each of the "words" and capitalize them
        for (var i = 0,len = split.length; i < len; i++) {
            split[i] = split[i].charat(0).toupperCase() + split[i].slice(1);
        }

        //re-join the string and set the value of the element
        this.value = split.join(' ');
    });
    return this;
};

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

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

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

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

更新

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

...
        for (var i = 0,len = split.length; i < len; i++) {
            split[i] = split[i].charat(0).toupperCase() + split[i].slice(1).toLowerCase();
        }
        ...

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

原文地址:https://www.jb51.cc/js/154318.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐