[removed] Scroll to selection after using textarea.setSelectionRange in Chrome

前端 未结 8 556
离开以前
离开以前 2020-12-31 05:05

A javascript function selects a certain word in a textarea using .setSelectionRange(). In Firefox, the textarea automatically scrolls down to show the selected text. In Chro

相关标签:
8条回答
  • 2020-12-31 05:41

    A lot of answers, but the accepted one doesn't consider line breaks, Matthew Flaschen didn't add the solution code, and naXa answer has a mistake. The simplest solution code is:

    textArea.focus();
    
    const fullText = textArea.value;
    textArea.value = fullText.substring(0, selectionEnd);
    textArea.scrollTop = textArea.scrollHeight;
    textArea.value = fullText;
    
    textArea.setSelectionRange(selectionStart, selectionEnd);
    
    0 讨论(0)
  • 2020-12-31 05:47

    You can see how we solved the problem in ProveIt (see highlightLengthAtIndex). Basically, the trick is to truncate the textarea, scroll to the end, then restore the second part of the text. We also used the textSelection plugin for consistent cross-browser behavior.

    0 讨论(0)
提交回复
热议问题