typing animation

jooog·2021년 9월 10일
0

자바스크립트로 text typing 효과 구현하기

CSS와 Javascript로 typing 효과를 만들어보자

먼저 css로 스크롤바 모양을 만든다

*SCSS

&-main::after {
        content:"";
        display: block;
        position: absolute;
        top:0;
        right:0;
        width:3px;
        height:100%;
        background-color: $color-white;
    }
    
    
&-main.active::after {
        display: none;
    }
   //active class가 붙으면 커서 모양이 안보이게 만든다

이후 타이핑 효과는 자바스크립트를 사용한다

먼저 커서가 깜빡이는 기능을 만들어보자

const blink = () => {
    text.classList.toggle("active")
}

//toggle로 active class가 붙었다 떼어지게하여
//커서가 깜빡이는 효과 구현한다

setInterval(blink, 500);
//setInterval로 시간간격을 주고 깜빡일 수 있도록 만든다

이제 타이핑 효과를 만들어보자

let text = document.querySelector('.heading-primary-main');
//타이핑효과가 들어갈 header section을 선택

let textString = ['Learn to JAVASCRIPT'];
//타이핑 효과를 줄 문자열을 배열로 작성

let selectText = textString[Math.floor(Math.random() * textString.length)]
//textString의 문자열을 random으로 뽑을 로직을 작성한다
//Math.random() * textString.length) 으로 random하게 숫자를 뽑아낸 후 Math.floor로 소수점 이하의 숫자를 제외한 random 숫자열을 만들 수 있다

문자열에서 하나씩 글자를 뽑는 방법

let splitText = selectText.split("");

//split을 사용하여 selectText문자열의 글자를 하나씩 뽑아낸다
const randomText = (randomArr) => {
    if (randomArr.length > 0) {
        text.textContent += randomArr.shift();

        setTimeout(function () {
            randomText(randomArr);
        }, 80);
    } else {
        setTimeout(restart, 3000);
        //3초 뒤 재실행
    }
}

randomText(resetTyping());
//randomText의 인자로 resetTyping함수를 넣어준다

ext.textContent += randomArr.shift();
shift를 사용하면 randomArr의 문자열의 글자를 하나씩 출력하는 효과를 만들 수 있다

const resetTyping = () => {
    let textString = ['Learn to CSS'];
    let selectText = textString[Math.floor(Math.random() * textString.length)]
    let splitText = selectText.split("");
    
    return splitText;
}


//randomText함수 실행이 끝나고 3초 후 재실행되는 restart함수
//restart함수는 다시 randomText함수를 호출하여 재실행된다

//타이핑 재실행
const restart = () => {
    text.textContent = '';
    randomText(resetTyping());
}

0개의 댓글