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

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

    Based on the idea from @naXa and @Valeriy Katkov, I refined the function with less bug. It should work out of the box (It's written with TypeScript. for JavasCript, just remove the type declariation) :

    function scrollTo(textarea: HTMLTextAreaElement, offset: number) {
        const txt = textarea.value;
        if (offset >= txt.length || offset < 0)
          return;
        textarea.scrollTop = 0;  // Important, so that scrollHeight will be adjusted
        textarea.value = txt.substring(0, offset);
        const height = textarea.scrollHeight;
        textarea.value = txt;
        textarea.scrollTop = height - 40;  // Margin between selection and top of viewport
    }
    

    Usage:

    let textarea, start, end;
    /* ... */
    
    scrollTo(textarea, start);
    textarea.focus();
    textarea.setSelectionRange(start, end);
    

提交回复
热议问题