我正在开发一个 cordova 应用程序。对于输入文本,我想为第一个字母启用键盘的大写锁定键。以前我使用 text-form:capitalise 但如果用户想要第一个字母小写,则不能再次将第一个字母更改为小写(大写属性不会在键盘上启用大写锁定键)。
只是我想在输入第一个字母时打开大写锁定键,如果用户禁用它,那么他可以将第一个字母输入为小写。
有任何 css、html、jquery、javascript 解决方案吗?我的应用程序中有多个文本字段,我希望该解决方案适用于所有输入类型 =“文本”。
我在下面输入的示例文本字段:
<input id="candidate_first_name" placeholder="Candidate First Name*"
type="text" class="ui-input-shadow-text">
最佳答案
您不能直接打开大写锁定或 shift 键。
您可以捕获按键事件,紧接着,如果该字段有一个字符,则将其设为大写。那么问题是避免弄乱用户的光标位置。在大多数现代浏览器上,您可以通过在更新字段后设置插入符位置来实现。如果用户不希望它被限制,他们将不得不返回并进行编辑,这是不理想的。
我不会在一般的网页中这样做(如果有的话),有太多的浏览器需要测试以避免让用户不满意的问题,但是如果你有一个更有限的场景并且可以用你的目标浏览器,这可能是可行的。
这是一个适用于当前 Chrome、Firefox、IE 和 iOS Safari 的示例:
$("#testing").on("keypress", function(e) {
// Only do it if the field is blank before the keypress
// (the event occurs before the character is added to
// the field)
if (this.value.length === 0) {
setTimeout(maybeCap.bind(this), 0);
}
});
function maybeCap() {
// Only do it if the field now has a single character
if (this.value.length == 1) {
this.value = this.value.toUpperCase();
setCaretPosition(this, 1);
}
}
function setCaretPosition(elem, caretPos) {
if (elem) {
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else
elem.focus();
}
}
}
<input type="text" id="testing">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
或者作为 jQuery 插件:
$.fn.capFirst = function() {
this.on("keypress", keypressHandler);
function keypressHandler(e) {
// Only do it if the field is blank before the keypress
// (the event occurs before the character is added to
// the field)
if (this.value.length === 0) {
setTimeout(maybeCap.bind(this), 0);
}
}
function maybeCap() {
// Only do it if the field now has a single character
if (this.value.length == 1) {
this.value = this.value.toUpperCase();
setCaretPosition(this, 1);
}
}
function setCaretPosition(elem, caretPos) {
if (elem) {
if (elem.createTextRange) {
var range = elem.createTextRange();
range.move('character', caretPos);
range.select();
} else {
if (elem.selectionStart) {
elem.focus();
elem.setSelectionRange(caretPos, caretPos);
} else
elem.focus();
}
}
}
};
$("input[type=text]").capFirst();
<div><input type="text"></div>
<div><input type="text"></div>
<div><input type="text"></div>
<div><input type="text"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
关于javascript - 键盘的大写锁定键如何锁定文本框的第一个字母?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29983389/