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

前端 未结 8 608
离开以前
离开以前 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:35

    Here is a simple and efficient solution, pure js :

    //first of all, you ignore any bad english, as i'm french and had a funny evening
    //get the textarea
    var textArea = document.getElementById('myTextArea');
    
    //define your selection
    var selectionStart = 50;
    var selectionEnd = 60;
    textArea.setSelectionRange( selectionStart, selectionEnd);
    
    // now lets do some math
    // we need the number of chars in a row
    var charsPerRow = textArea.cols;
    
    // we need to know at which row our selection starts
    var selectionRow = (selectionStart - (selectionStart % charsPerRow)) / charsPerRow;
    
    // we need to scroll to this row but scrolls are in pixels,
    // so we need to know a row's height, in pixels
    var lineHeight = textArea.clientHeight / textArea.rows;
    
    // scroll !!
    textArea.scrollTop = lineHeight * selectionRow;
    

    Put this in a function, extend the prototype of javascript's Element object with it, and you're good.

    Feel free to ask if you need any further help.

提交回复
热议问题