Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
612 views
in Technique[技术] by (71.8m points)

javascript - Set cursor to specific position on specific line in a textarea

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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(" ")); 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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...