2015-08-15 89 views
2

如何將光標移動到使用Javascript的textarea中的下一個或上一個單詞?我試圖在HTML textarea中複製Emacs命令「前進一個單詞」和「後退一個單詞」。如何將光標移動到textarea中的下一個/上一個單詞?

我可以使用rangyinputs獲得當前光標/光標位置,但我不確定如何有效地移動到下一個單詞,而不使用各種分割,這些分割對於很長的文本可能會很慢。

+0

你嘗試過什麼嗎? –

+0

這可能會有所幫助:http://stackoverflow.com/questions/499126/jquery-set-cursor-position-in-text-area – Anders

+0

@AlexTartan已添加 –

回答

1

我用setCaretToTextEnd()here.selectRange()here。以下函數使用Emacs風格的插入位置,並且比循環單詞更高效。

function nextWord(input) { 
    let currentCaretPosition = input.selectionStart; 

    // -1 Because Emacs goes to end of next word. 
    let nextWordPosition = input.value.indexOf(' ', currentCaretPosition) - 1; 
    if (nextWordPosition < 0) { 
    input.setCaretToTextEnd(); 
    } else { 
    input.selectRange(nextWordPosition); 
    } 
} 

function previousWord(input) { 
    let currentCaretPosition = input.selectionStart; 

    // +1 Because Emacs goes to start of previous word. 
    let previousWordPosition = input.value.lastIndexOf(' ', currentCaretPosition) + 1; 
    if (previousWordPosition < 0) { 
    input.selectRange(0); 
    } else { 
    input.selectRange(previousWordPosition); 
    } 
} 
0

看到這個fiddle。我使用jQuery Set Cursor Position in Text Area中的函數來改變光標的位置。

function nextWord(input) { 
    var words = input.value.split(" "), 
     index = 0; 
    for (var i in words) { 
     var word = words[i]; 
     if (index+word.length >= input.selectionStart) { 
      setCaretToPos(input, index+word.length+1); 
      break; 
     } 
     index += word.length+1; 
    } 
} 
function previousWord(input) { 
    var words = input.value.split(" ").reverse(), 
     index = input.value.length; 
    for (var i in words) { 
     var word = words[i]; 
     if (index+1 <= input.selectionStart) { 
     setCaretToPos(input, index-word.length); 
      break; 
     } 
     index -= word.length+1; 
    } 
} 
相關問題