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

前端 未结 8 587
离开以前
离开以前 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);
    

提交回复
热议问题