您还可以在 keyup 上设置光标位置(或者您正在使用的任何内容,只要您获得对输入元素的引用)
function withSelectionRange() {
const elem = document.getElementById('working');
// get start position and end position, in case of an selection these values
// will be different
const startPos = elem.selectionStart;
const endPos = elem.selectionEnd;
elem.value = elem.value.toUpperCase();
elem.setSelectionRange(startPos, endPos);
}
function withoutSelectionRange() {
const elem = document.getElementById('notWorking');
elem.value = elem.value.toUpperCase();
}
<div style="display: flex; flex-direction: column">
<label for='working'>Uppercase text with selection range</label>
<input id='working' type='text' onkeyup="withSelectionRange()"></input>
<label for='notWorking'>Uppercase text input without selection range</label>
<input id='notWorking' type='text' onkeyup="withoutSelectionRange()"></input>
</div>
您只需添加一些 CSS 样式即可实现此目的:
#example {
text-transform: uppercase;
}
这将使输入字段中的所有字母显示为大写,但值仍然相同。如果您需要将该值设置为大写,请在需要时将其转换为大写(例如在提交之前)
我一直在寻找同一问题的解决方案。
添加 CSS 对我来说很有效,除了有一个特定要求,即我们的后端 api 只接受大写字符串。
所以除此之外:
#example {
text-transform: uppercase;
}
我还添加了监听
onBlur
和 keydown.enter
的回调,并在触发这些事件时将输入值转换为大写。
最好的方法是在新文件中创建指令
import { DefaultValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';
import {
Directive,
ElementRef,
HostListener,
Renderer2,
forwardRef,
} from '@angular/core';
@Directive({
selector: 'input[toUppercase]',
providers: [
{
provide: NG_VALUE_ACCESSOR,
multi: true,
useExisting: forwardRef(() => UpperCaseInputDirective),
},
],
})
export class UpperCaseInputDirective extends DefaultValueAccessor {
@HostListener('keyup', ['$event']) input($event: InputEvent) {//keyup yesssss sa
const target = $event.target as HTMLInputElement;
const start = target.selectionStart;
target.value = target.value.toUpperCase();
target.setSelectionRange(start, start);
this.onChange(target.value);
}
constructor(renderer: Renderer2,
elementRef: ElementRef) {
super(renderer, elementRef, false);
}
}
在app.module.ts中
@NgModule({
declarations: [
UpperCaseInputDirective,
在你的 html 组件中
<input toUppercase>