티스토리 뷰

728x90
반응형

 textarea 영역 자동 크기 조절

textarea에 글을 입력시 다음줄로 넘길때 마다 자동으로 크기를 조절해 준다.

조으다.

 

http://www.jacklmoore.com/autosize/

 

Autosize

Autosize A small, stand-alone script to automatically adjust textarea height. Demo Released under the MIT License, source on Github (changelog)   Download Install via NPM npm install autosize Browser compatibility Chrome Firefox IE Safari iOS Safari Andro

www.jacklmoore.com

 

이것말고도 러프하지만 직접 코드를 작성해 보았다.

 

 export class Utils {
 
   public static txtAreaEleH(txtAreaEle: HTMLTextAreaElement, txt: string) {
        
        let txtAreaSizeTotal=0;
        // tslint:disable-next-line:prefer-for-of
        for (let i=0; i < txt.length; i++) {
            //영문/한글 섞인 문자를 바이트 수 계산
            txtAreaSizeTotal+=Utils.getCharByteSize( txt.charAt( i ) );
        }
        const lineH=20; //한줄 높이 
        const maxTxtLen=117; //한줄에 최대한 들어갈 수 있는 텍스트의 바이트 수 - 영문/한글 섞인 계산된 바이트 수
        const lineInLen=txtAreaSizeTotal / maxTxtLen; //maxTxtLen , 즉 몇줄까지 입력되었는 지 라인 수 계산
        const numOfLine: number=(txt.match( /\n/g ) || []).length; // 엔터키가 몇개 들어 갔는 지 체크
        const resultH=lineH + (lineInLen + numOfLine) * lineH; //1줄 높이( 20px )+( 텍스트 입력 라인 수+엔터키 개수 ) * 1줄 높이( 20px )

        txtAreaEle.style.height=resultH + 'px';
    }


    /**
     * 문자열 여러개 중 개별 1개 문자에 대한 바이트 계산
     * @param txt 문자
     * @returns {number}
     */
    public static getCharByteSize(txt: string): number {
        if (txt === null || txt.length === 0) {
            return 0;
        }
        //byte 는 -128 ~ 127 까지  0x00 ~ 0xFF (1 바이트)
        //2byte = 16bit = 2^16 = 65,536
        const charCode=txt.charCodeAt( 0 );
        if (charCode <= 127) {  //0x00007F
            return 1;
        } else if (charCode <= 2047) { //0x0007FF
            return 2;
        } else if (charCode <= 65535) { //0x00FFFF
            return 3;
        } else {
            return 4;
        }
    }
    
 }
728x90
반응형
댓글