在 CSS 中使输入值大写而不影响占位符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/25180140/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 02:27:27  来源:igfitidea点击:

Make input value uppercase in CSS without affecting the placeholder

cssuppercase

提问by kaleazy

Is there a way I can make an input value uppercase without making the placeholder uppercase?

有没有一种方法可以使输入值大写而不使占位符大写?

Seems like I get one or the other. I'd prefer to do this cleanly just using CSS (JS last resort).

好像我得到了一个。我更愿意只使用 CSS(JS 最后的手段)干净利落地做到这一点。

enter image description here

enter image description here

回答by Sander Koedood

Each browser engine has a different implementation to control placeholderstyling. Use the following:

每个浏览器引擎都有不同的实现来控制placeholder样式。使用以下内容:

jsBin example.

jsBin 示例。

input { 
    text-transform: uppercase;
}
::-webkit-input-placeholder { /* WebKit browsers */
    text-transform: none;
}
:-moz-placeholder { /* Mozilla Firefox 4 to 18 */
    text-transform: none;
}
::-moz-placeholder { /* Mozilla Firefox 19+ */
    text-transform: none;
}
:-ms-input-placeholder { /* Internet Explorer 10+ */
    text-transform: none;
}
::placeholder { /* Recent browsers */
    text-transform: none;
}

Needless to say, this only works in browsers that can handle placeholders. (IE9/10+)

不用说,这只适用于可以处理占位符的浏览器。(IE9/10+)

回答by Yehuda Schwartz

I know you said using JS was a last resort however in this case it is probaly more effective and simpler (also if you dont use JS you the value posted on frorm submit will not be uppercase) so this might be better no aditional CSS needed:

我知道你说使用 JS 是最后的手段,但在这种情况下,它可能更有效和更简单(如果你不使用 JS,那么提交时发布的值将不会是大写的)所以这可能更好,不需要额外的 CSS:

<input oninput="this.value = this.value.toUpperCase()" placeholder="Enter Drivers License #" />

EDIT

编辑

Some people have been complaining that the cursor jumps to the end when editing the value, so this slightly expanded version should resolve that

有些人一直在抱怨编辑值时光标会跳到最后,所以这个稍微扩展的版本应该可以解决这个问题

<input oninput="let p = this.selectionStart; this.value = this.value.toUpperCase();this.setSelectionRange(p, p);" />