您的代码是正确的,但元素对事件<textarea>
做出反应,而不是.keypress
keydown
无论如何,为什么这么复杂?您可以设置input.value
然后使用input.setSelectionRange()
方法适当地移动光标。如果你想在当前行的末尾添加一些东西,你可以这样做:
var position = objTag.selectionStart;
var lineEnd = objTag.value.indexOf("\n", position);
if (lineEnd < 0) // No more line breaks
lineEnd = objTag.value.length;
var textToAdd = "foo";
objTag.value = objTag.value.substr(0, lineEnd) + textToAdd + objTag.value.substr(lineEnd);
objTag.setSelectionRange(lineEnd + textToAdd.length, lineEnd + textToAdd.length);
objTag.focus();
添加到文本的末尾甚至更简单:
var textToAdd = "foo";
objTag.value += textToAdd;
objTag.setSelectionRange(objTag.value.length, objTag.value.length);
objTag.focus();