How to get the height of the text inside of a textarea

后端 未结 8 1624
眼角桃花
眼角桃花 2020-12-05 10:02

I have a textarea with the the text Hello World. I would like to get the height of this text.

I\'ve tried to use:

var eleme         


        
8条回答
  •  情歌与酒
    2020-12-05 10:43

    For anyone using React:

    const textarea_ref = useRef(null);
    const [idealHeight,setIdealHeight] = useState(0);
    const [inputValue,setInputValue] = useState("");
    
    
    useLayoutEffect(() => {                                           // useLayoutEffect TO AVOID FLICKERING
        textarea_ref.current.style.height = '0px';                    // NEEDS TO SET HEIGHT TO ZERO
        const scrollHeight = textarea_ref.current.scrollHeight;       // TO READ THE CORRECT SCROLL HEIGHT WHEN IT SHRINKS
        textarea_ref.current.removeAttribute('style');                // REMOVE INLINE STYLE THAT WAS ADDED WITH 0px
        setIdealHeight(scrollHeight + 2);                             // NEEDS TO ADD 2. I THINK IT'S BECAUSE OF THE BORDER
      },[inputValue]);
    
    return (