使用JQuery实时利用用户输入的第一个字符 [英] Capitalize first character of user input in real time with JQuery
问题描述
我正在尝试自动大写用户输入的textarea / input的第一个字符。第一次尝试看起来像这样:
I am trying to auto-capitalize the first character of a textarea/input that the user inputs. The first attempt looked like this:
$(document).ready(function() {
$('input').on('keydown', function() {
if (this.value[0] != this.value[0].toUpperCase()) {
// store current positions in variables
var start = this.selectionStart;
var end = this.selectionEnd;
this.value = this.value[0].toUpperCase() + this.value.substring(1);
// restore from variables...
this.setSelectionRange(start, end);
}
});
});
这个问题是它显示小写字符,然后更正它,这很难看(< a href =http://jsfiddle.net/9zPTA/2/> http://jsfiddle.net/9zPTA/2/ )。我想在keydown而不是keyup上运行我的javascript,并在飞行中转换事件(或拦截它,防止默认,并触发修改后的新事件)。
The problem with this is that it shows the lowercase character and then corrects it, which is ugly (http://jsfiddle.net/9zPTA/2/). I would like to run my javascript on keydown instead of keyup, and transform the event in flight (or intercept it, prevent default, and trigger a modified new event).
这是我现在所拥有的,但不起作用( http://jsfiddle.net/9zPTA/5/ ):
Here's what I have now, which doesn't work (http://jsfiddle.net/9zPTA/5/):
$(document).ready(function() {
$('input').on('keydown', function(event) {
if (this.selectionStart == 0 && event.keyCode >= 65 && event.keyCode <= 90 && !(event.shiftKey)) {
event.preventDefault();
var myEvent = jQuery.Event('keypress');
myEvent.target = event.target;
myEvent.shiftKey = true;
myEvent.keyCode = event.keyCode;
$(document).trigger(myEvent);
}
});
});
我不确定为什么这不起作用 - 我在这里缺少什么?
I'm not sure why this doesn't work - what am I missing here?
推荐答案
这里是我制作的小提琴,可以在Chrome中执行您想要的操作。我不确定它是否适用于其他浏览器。
Here is a fiddle I made that does what you want in Chrome. I'm not sure if it will work in other browsers.
代码:
$(document).ready(function() {
$('input').on('keydown', function(event) {
if (this.selectionStart == 0 && event.keyCode >= 65 && event.keyCode <= 90 && !(event.shiftKey) && !(event.ctrlKey) && !(event.metaKey) && !(event.altKey)) {
var $t = $(this);
event.preventDefault();
var char = String.fromCharCode(event.keyCode);
$t.val(char + $t.val().slice(this.selectionEnd));
this.setSelectionRange(1,1);
}
});
});
这篇关于使用JQuery实时利用用户输入的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!