Javascript 在不丢失光标位置的情况下更新输入的值
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14508707/
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
Updating an input's value without losing cursor position
提问by nice ass
I want to mandate that the value of a text box is lowercase using JavaScript. I've tried the code below, but the cursor jumps to the end of the input every time you press a key. How can I avoid this?
我想使用 JavaScript 强制文本框的值是小写的。我已经尝试了下面的代码,但是每次按下一个键时,光标都会跳到输入的末尾。我怎样才能避免这种情况?
$("#beLowerCase").keyup(function(){
$(this).val( $(this).val().toLowerCase() );
});
回答by nice ass
$("#beLowerCase").on('input', function(){
// store current positions in variables
var start = this.selectionStart,
end = this.selectionEnd;
this.value = this.value.toLowerCase();
// restore from variables...
this.setSelectionRange(start, end);
});
(fiddle)
(小提琴)
This actually works with CSS as well:
这实际上也适用于 CSS:
#beLowerCase{
text-transform:lowercase;
}
And server can take care of the actual lower-casing...
并且服务器可以处理实际的小写...

