How to stop window jumping when typing in autoresizing textarea

后端 未结 4 1787
一整个雨季
一整个雨季 2020-12-21 06:35

I am using the accepted answer to this question to build a textarea that expands vertically as text overflows:





        
4条回答
  •  南笙
    南笙 (楼主)
    2020-12-21 07:13

    Save the scrollLeft, scrollTop values, and then restore them after resizing the textarea:

    function resize () {
       var scrollLeft = window.pageXOffset ||
       (document.documentElement || document.body.parentNode || document.body).scrollLeft;
    
       var scrollTop  = window.pageYOffset ||
       (document.documentElement || document.body.parentNode || document.body).scrollTop;
    
       text.style.height = "auto";
       text.style.height = text.scrollHeight + 'px';
    
       window.scrollTo(scrollLeft, scrollTop);
    }
    

    JSFiddle: http://jsfiddle.net/losnir/nnkeH/1

提交回复
热议问题