· FRONT-END/└ JS

[ JavaScript ] 스크립트에서 폰트 조절하기

감자도리22 2024. 5. 5. 13:54

환경 : Visual Studio Code

 

 

- 버튼을 활용하여 글자 크기를 조절해보자

 

출력결과 (하단 영상 참고)

 

 [1] 작게 / 보통 / 크게 버튼으로 조절

    <script type="text/javascript">
        
        function smallText(){
            var target = document.querySelector(".txt");
            target.style.fontSize = "12px";
        }

        function normalText(){
            var target = document.querySelector(".txt");
            target.style.fontSize = "16px";
        }

        function bigText(){
            var target = document.querySelector(".txt");
            target.style.fontSize = "24px";
        }
    </script>
</head>
<body>
    <div class="container w-500">
        <div class="cell center">
            <h1>폰트 크기 조절하기</h1>
        </div>
        <div class="cell">
            <button class="btn" onclick="smallText();">작게</button>
            <button class="btn" onclick="normalText();">보통</button>
            <button class="btn" onclick="bigText();">크게</button>
            <hr>
            <textarea class="txt" style="font-size: 16px; width: 100%;">
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </textarea>
        </div>
    </div>
</body>
</html>

    (+) 각 버튼별 함수를 만들어 폰트 크기를 지정. 

 


 

[2] - / + 버튼을 활용하여 1px씩 감소/증가 시키기

    <script type="text/javascript">

        //심화
        function minusText(){
            var target = document.querySelector("[name=content]");
            var spanTarget = document.querySelector(".show");
            
            var cfontSize = parseInt(target.style.fontSize) - 1;
            if(cfontSize <= 8) return; //조건 필수
            
            console.log(cfontSize);
            target.style.fontSize = cfontSize + "px";
            spanTarget.textContent = cfontSize;
        }

        function plusText(){
            var target = document.querySelector("[name=content]");
            var spanTarget = document.querySelector(".show");

            var cfontSize = parseInt(target.style.fontSize) + 1;
            if(cfontSize > 40) return;//조건 필수
            
            console.log(cfontSize);
            target.style.fontSize = cfontSize + "px"; //px을 붙여줘야 한다
            spanTarget.textContent = cfontSize;
        }
    </script>
</head>
<body>

    <!-- 심화 -->
    <div class="container w-500">
        <div class="cell center">
            <h1>폰트 크기 조절하기(심화)</h1>
        </div>
        <div class="cell">
            <button class="btn" onclick="minusText();">
                <i class="fa-solid fa-minus" style="color: #b3c4df;"></i>
            </button>
            <span class="show"> 16 </span>
            <button class="btn" onclick="plusText();">
                <i class="fa-solid fa-plus" style="color: #b3c4df;"></i>
            </button>

            <hr>
            <textarea class="text" name="content" style="font-size: 16px; width: 100%;">
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </textarea>
        </div>
    </div>
   

</body>
</html>

      (+) parseInt(target.style.fontSize) : 폰트 사이즈를 가져와서 적용하기

      (+) 글씨가 일부 크기를 넘어가면 더 이상 줄어들지 않도록 각각 조건 부여 (8이하, 40 초과)

 

 

    - (추가) parseInt() 차이 이해

콘솔창 확인

 

     (+) parseInt() 함수를 적용하지 않은 결과 : 16px

     (+) parseInt() 함수를 적용한 결과 : 16

                           


 

[3] 함수를 하나로 합치기 (추가공부)

    <script type="text/javascript">
        function adjustText(size){
            var target = document.querySelector("[name=content]");
            var spanTarget = document.querySelector(".show");

            if(size == 0){
                var cfontSize = parseInt(target.style.fontSize) - 1;
                if(cfontSize <= 8) return;
            } else {
                var cfontSize = parseInt(target.style.fontSize) + 1;
                if(cfontSize > 40) return;
            }
            
            target.style.fontSize = cfontSize + "px";
            spanTarget.textContent = cfontSize;
        }
    </script>
</head>
<body>
    <div class="container w-500">
        <div class="cell center">
            <h1>폰트 크기 조절하기(심화)</h1>
        </div>
        <div class="cell">
            <button class="btn" onclick="adjustText(0);">
                <i class="fa-solid fa-minus" style="color: #b3c4df;"></i>
            </button>
            <span class="show"> 16 </span>
            <button class="btn" onclick="adjustText(1);">
                <i class="fa-solid fa-plus" style="color: #b3c4df;"></i>
            </button>

            <hr>
            <textarea class="text" name="content" style="font-size: 16px; width: 100%;">
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </textarea>
        </div>
    </div>
</body>
</html>

    (+) 매개변수에 값을 부여하여 그 값에 따른 조건식을 활용하여 합수를 하나로 합침

 


   - (추가) 폰트 사이즈를 스크립트에서 지정해주는 방법 3가지

target.style = "font-size:12px";
target.style.fontSize = "12px";//여러 단어일 경우 카멜케이스로 작성
target.style["font-size"] = "12px";//자바스크립트 객체 접근 방식(자바의 MAP 과 유사)

   - 실행 결과

실행결과

 


[ 전체 코드 ]

<!DOCTYPE html>
<html lang="ko">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Javascript 예제</title>

    <!-- 구글 폰트 -->
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Noto+Sans+KR:wght@100..900&display=swap" rel="stylesheet">
     
    <!-- 내가 구현할 스타일 -->
    <link rel="stylesheet" type="text/css" href="../css/commons.css">
    <link rel="stylesheet" type="text/css" href="../css/test.css">
    
    <!-- font awesome 아이콘 CDN -->
    <link rel="stylesheet" type="text/css" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css">
    
    <style>

    </style>

    <!-- javascript를 의도적으로 head 자리에 배치해서 가장 먼저 실행되도록 구현 -->
    <script type="text/javascript">
        
        function smallText(){
            var target = document.querySelector(".txt");
            target.style.fontSize = "12px";
        }

        function normalText(){
            var target = document.querySelector(".txt");
            target.style.fontSize = "16px";
        }

        function bigText(){
            var target = document.querySelector(".txt");
            target.style.fontSize = "24px";
        }

        //심화
        /*function minusText(){
            var target = document.querySelector("[name=content]");
            var spanTarget = document.querySelector(".show");
            
            var cfontSize = parseInt(target.style.fontSize) - 1;
            if(cfontSize <= 8) return;
            
            console.log(cfontSize);
            target.style.fontSize = cfontSize + "px";
            spanTarget.textContent = cfontSize;
        }

        function plusText(){
            var target = document.querySelector("[name=content]");
            var spanTarget = document.querySelector(".show");

            var cfontSize = parseInt(target.style.fontSize) + 1;
            if(cfontSize > 40) return;
            
            console.log(cfontSize);
            target.style.fontSize = cfontSize + "px";
            spanTarget.textContent = cfontSize;
        }*/

        function adjustText(size){
            var target = document.querySelector("[name=content]");
            var spanTarget = document.querySelector(".show");

            //console.log(target.style.fontSize);
            //console.log(parseInt(target.style.fontSize));


            if(size == 0){
                var cfontSize = parseInt(target.style.fontSize) - 1;
                if(cfontSize <= 8) return;
            } else {
                var cfontSize = parseInt(target.style.fontSize) + 1;
                if(cfontSize > 40) return;
            }
            
            //console.log(cfontSize);
            target.style.fontSize = cfontSize + "px";
            spanTarget.textContent = cfontSize;
        }
    </script>
</head>
<body>


    <div class="container w-500">
        <div class="cell center">
            <h1>폰트 크기 조절하기</h1>
        </div>
        <div class="cell">
            <button class="btn" onclick="smallText();">작게</button>
            <button class="btn" onclick="normalText();">보통</button>
            <button class="btn" onclick="bigText();">크게</button>
            <hr>
            <textarea class="txt" style="font-size: 16px; width: 100%;">
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </textarea>
        </div>
    </div>

    <!-- 심화 -->
    <div class="container w-500">
        <div class="cell center">
            <h1>폰트 크기 조절하기(심화)</h1>
        </div>
        <div class="cell">
            <button class="btn" onclick="adjustText(0);">
                <i class="fa-solid fa-minus" style="color: #b3c4df;"></i>
            </button>
            <span class="show"> 16 </span>
            <button class="btn" onclick="adjustText(1);">
                <i class="fa-solid fa-plus" style="color: #b3c4df;"></i>
            </button>

            <hr>
            <textarea class="text" name="content" style="font-size: 16px; width: 100%;">
                Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.
            </textarea>
        </div>
    </div>
   

</body>
</html>

 

 

 

개인 공부 기록용입니다:)

728x90