set cursor to specific position on specific line in a textarea

南笙酒味 提交于 2019-11-26 14:48:56

问题


I am trying to somewhat duplicate the "autocorrect" functionality seen in programs like Microsoft Office's Outlook.

For starters, anytime a user types "a " (the letter a and a space) at the beginning of a line I want to change that text to "*Agent ["

I have written the below which works fine if you are typing along in the textarea from top to bottom. But if you type anywhere else in the textarea the text is changed then the cursor moves to the end of the textarea.

I want the cursor to always be placed at the end of the changed text.

I have the line number that was changed in the variable currentLineNumber and i know the cursor needs to be after the 8th character in that line but I am unsure of how to tell it to go there

Ideally id like to something like

function setCursor(row, position) {
 //.... code to set cursor 
}

What can I do to accomplish this? Im open to a javascript or jQuery solution (although I find jQuery a little difficult to read and understand)

If there's a better way to achieve what I need overall, I'm open to that too.

Here's a jsFiddle if you don't understand the issue


回答1:


I've updated your fiddle see: http://jsfiddle.net/eghpf/2/

I've added var currentPosition which is used in this method

function setSelectionRange(input, selectionStart, selectionEnd) {
  if (input.setSelectionRange) {
    input.focus();
    input.setSelectionRange(selectionStart, selectionEnd);
  }
  else if (input.createTextRange) {
    var range = input.createTextRange();
    range.collapse(true);
    range.moveEnd('character', selectionEnd);
    range.moveStart('character', selectionStart);
    range.select();
  }
}

Which comes from this jQuery Set Cursor Position in Text Area

What happens (is the reason why the cursor is always on the last position); is when you call $('#systemNotesbuilder').val(arrayOfLines.join("\n")); the entire value gets overwritten with a new value placing the cursor after that new value. The call to set the cursor is (and should) be after that call.



来源:https://stackoverflow.com/questions/17858174/set-cursor-to-specific-position-on-specific-line-in-a-textarea

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!