How to stop window jumping when typing in autoresizing textarea

后端 未结 4 1788
一整个雨季
一整个雨季 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:01

    A way to do the accepted answer when the textarea is in a scrollable div:

    function getScrollParent(node) {
        if (node == null) {
            return null;
        }
    
        if (node.scrollHeight > node.clientHeight) {
            return node;
        } else {
            return getScrollParent(node.parentNode);
        }
    }
    
    function resize(){
        // 'this' is the textarea
        const scrollParent = getScrollParent(this);
        const scrollTop = scrollParent ? scrollParent.scrollTop : null;
        const scrollLeft = scrollParent ? scrollParent.scrollLeft : null;
    
        this.style.height = "auto";
        this.style.height = this.scrollHeight + "px";
    
        if (scrollParent) {
            scrollParent.scrollTo(scrollLeft, scrollTop);
        }
    };
    

提交回复
热议问题