如何捕获由 css 大写的大写输入字母:文本转换:大写

How to capture capitalized input letter which is capitalized by css: text-transform:capitalize

本文关键字:文本 大写 转换 何捕获 css 输入      更新时间:2023-09-26

我发现用css大写的大写字母text-transform:capitalize在被javascript捕获时没有大写。我想知道解决此问题的最简单方法是什么?

下面的演示:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
<input id="box" type="text" style="text-transform:capitalize">
<button id="showinput">type in something then press me</button>
</html>
<script>
$("#showinput").click(function(){
txt=$("#box").val();
alert(txt+"   as you can see, the first letter of each word is not capitalized!");
})
</script>
CSS 文本转换属性

仅转换用户在屏幕上看到的内容(与所有 CSS 属性一样)。它不会与你的 JavaScript 代码交互。我建议对 JavaScript 中的字符串应用类似的函数,例如 lodash 中的_.upperCase

正如 McMath 所说,CSS text-transform 不与 Javascript 交互。这是一个解决方案,可以通过在 Javascript 中大写第一个字母来给出您想要的结果:

$("#showinput").click(function(){
  txt = $("#box").val();
  txt = txt.charAt(0).toUpperCase() + txt.slice(1);
  alert(txt+"   as you can see, the first letter of each word is capitalized!");
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<html>
  <input id="box" type="text" style="text-transform:capitalize">
  <button id="showinput">type in something then press me</button>
</html>

来源:如何在 JavaScript 中使字符串的第一个字母大写?

使用正则表达式在 js 中执行此操作

    $("#showinput").click(function(){
    txt=$("#box").val();
    txt = txt.trim().replace(/'b'w{3,}/g, function (l) {
      return l.charAt(0).toUpperCase() + l.slice(1);
    });
    alert(txt+"   as you can see, the first letter of each word is not capitalized!");
    })
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html>
    <input id="box" type="text" style="text-transform:capitalize">
    <button id="showinput">type in something then press me</button>
    </html>

测试用例:Hello World

注意 这也适用于输入的文本之间有空格的情况,样式text-transform:capitalize处理每个单词大写的情况。

小提琴

脚本

$("#showinput").click(function(){
txt=$("#box").val();
var newtxt=txt.split(" ");
var tmp=[];
for(i=0;i<newtxt.length;i++)
{
    tmp.push(newtxt[i].trim().charAt(0).toUpperCase()+ newtxt[i].slice(1));
}
//alert(tmp.join(" "));//YOU CAN USE THIS ALSO
alert(tmp.join().replace(","," ")+"   as you can see, the first letter of each word is not capitalized!");//YOU CAN USE tmp.join(" ") also
})

描述

我尝试的是,首先获取数组中的每个单词,由space分割。然后转换每个单词的第一个字母,同时修剪任何空格,然后将其与单词的其余部分连接起来,并将其全部放入数组中。

然后用 .join() 连接数组,然后用 space 替换,。我希望这对你有帮助。

参见小提琴演示,它像你说的那样工作。