是否可以使用 JavaScript 或 jQuery 在用户键入时更改文本输入字段的内容?
例如输入 a + up
会将 a
更改为 å
,同时将输入光标保持在同一位置。
最佳答案
是的,即时更改它并保持 selectionStart
和 selectionEnd
在以前的位置:http://jsfiddle.net/pimvdb/p2jL3/3/ .
selectionStart
和selectionEnd
表示选择范围,当没有选择时它们是相等的,此时它们表示光标位置。
编辑:决定为它制作一个 jQuery 插件,因为它以后可能会派上用场,而且很容易以这种方式在任何地方实现。
(function($) {
var down = {}; // keys that are currently pressed down
replacements = { // replacement maps
37: { // left
'a': 'ã'
},
38: { // up
'a': 'â'
},
39: { // right
'a': 'á'
},
40: { // down
'a': 'à'
}
};
$.fn.specialChars = function() {
return this.keydown(function(e) {
down[e.keyCode] = true; // this key is now down
if(down[37] || down[38] || down[39] || down[40]) { // if an arrow key is down
var value = $(this).val(), // textbox value
pos = $(this).prop('selectionStart'), // cursor position
char = value.charAt(pos - 1), // old character
replace = replacements[e.keyCode][char] || char; // new character if available
$(this).val(value.substring(0, pos - 1) // set text to: text before character
+ replace // + new character
+ value.substring(pos)) // + text after cursor
.prop({selectionStart: pos, // reset cursor position
selectionEnd: pos});
return false; // prevent going to start/end of textbox
}
}).keyup(function(e) {
down[e.keyCode] = false; // this key is now not down anymore
}).blur(function() {
down = {}; // all keys are not down in the textbox when it loses focus
});
};
})(jQuery);
关于javascript - 更改输入值,同时仍允许用户键入,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7217176/