我正在设置一个用于输入西类牙语动词的表单。我希望能够使用js-hotkeys插件来创建添加重音字母的快捷方式。
到目前为止我已经有了
$('#presentTense input').bind('keyup', 'Ctrl+a', function () {
this.value = this.value + ('á');
});
这很好,因为他们正在打字,并且它将重音字母添加到他们键入的内容的末尾。问题是,如果他们想返回并将重音字母插入到已键入的单词中间以修复错误或遗漏,则此方法会将重音字母添加到单词的末尾。
谁能告诉我一种方法,用于在输入文本字段中的光标所在位置插入字母,无论是在单词的末尾还是中间?
最佳答案
嗨,我在 this question 中找到了这个片段
(function($) {
$.fn.getCursorPosition = function() {
var input = this.get(0);
if (!input) return; // No (input) element found
if ('selectionStart' in input) {
// Standard-compliant browsers
return input.selectionStart;
} else if (document.selection) {
// IE
input.focus();
var sel = document.selection.createRange();
var selLen = document.selection.createRange().text.length;
sel.moveStart('character', -input.value.length);
return sel.text.length - selLen;
}
}
})(jQuery);
这将使您能够找到单词处的光标位置,如下所示:
$('#presentTense input').getCursorPosition();
之后,您只需将字符串视为数组并将值插入其中,然后将其余部分向右移动。
关于javascript - js-hotkeys 在表单中的单词中间添加字母,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27628464/