궁금한 내용을 검색해보세요!
이 포스팅은 쿠팡 파트너스 활동의 일환으로, 이에 따른 일정액의 수수료를 제공받습니다.
서근 개발노트
티스토리에 팔로잉
FRONT-END/JAVASCRIPT

타이핑 하고 지우는 Javascript

서근
QUOTE THE DAY

-
Written by SeogunSEOGUN

반응형

이번에는 타이핑을 하고 지우는 효과를 javascript로 만들어 보도록 하겠습니다.

타이핑하는 자바스크립트

이 스크립트는 제 블로그 홈에 사용됐는데 아래와 같이 활용 가능합니다.

 

만약 티스토리 스킨편집에 대한 기초 지식이 없으시다면 아래 글을 먼저 읽고 와주세요!

 

(티스토리) 스킨 편집 기초 상식

안녕하세요. 제 블로그에는 티스토리에서 스킨을 적용하기 위해 다양한 포스팅이 존재합니다. 이번에는 티스토리에서 어떻게 스킨을 어떻게 편집하는지 아주 간단하게 알아보려고 합니다. 스

seons-dev.tistory.com

우선 커서가 깜빡이는 것부터 만들어보겠습니다.

커서 만들기

html 부분에 typeText 클래스를 하나 생성해줍니다.

<div class="container">
  <p class="textAbove">안녕하세요</p>
  <p class="typeText"></p>
</div>

그리고 CSS에 애니메이션과 함께 커서를 추가합니다.

.typeText::after {
  content: "|";
  animation: blink 1s step-end infinite;
  color: #fff;
}

@keyframes blink {
  0% {
    opacity:1;
  }
  49% {
    opacity:1;
  }
  50% {
    opacity:0;
  }
  100% {
    opacity:0;
  }
}

typeText의 뒤쪽에 커서가 위치해야 하기 때문에 ::after 키워드를 사용해서 커서처럼 보이게 애니메이션 효과를 줬습니다.

Javascript

이제 타이핑 효과를 낼 수 있도록 자바스크립트를 다음과 같이 작성합니다.

var typeText = document.querySelector(".typeText")
var textToBeTyped = "개발자"
var index = 0, isAdding = true

function playAnim() {
  setTimeout(function () {
    // set the text of typeText to a substring of
    // the textToBeTyped using index.
    typeText.innerText = textToBeTyped.slice(0, index)
    if (isAdding) {
      // adding text
      if (index > textToBeTyped.length) {
        // no more text to add
        isAdding = false
        //break: wait 2s before playing again
        setTimeout( function () {
          playAnim()
        }, 2000)
        return
      } else {
        // increment index by 1
        index++
      }
    } else {
      // removing text
      if (index === 0) {
        // no more text to remove
        isAdding = true
      } else {
        // decrement index by 1
        index--
      }
    }
    // call itself
    playAnim()
  }, 120)
}
// 타이핑 스크립트 호출
playAnim()

setTimout을 사용해서 120ms 마다 반복적으로 playAnim()을 실행하게 됩니다.

 

그리고 타이핑이 끝나면 2초 정도 머물렀다가 타이핑을 지우게 됩니다.

See the Pen Untitled by 서근 (@seogun95) on CodePen.

텍스트 여러개 사용하기 

배열을 사용해서 여러 개의 단어를 작성할 수 도 있습니다.

var typeText = document.querySelector(".typeText")
var textToBeTyped = "서근입니다."
var textToBeTypedArr = ["서근입니다.", "환영합니다", "오늘도 즐거운하루", "보내세요!"]
var index = 0, isAdding = true, textToBeTypedIndex = 0

function playAnim() {
  setTimeout(function () {
    // set the text of typeText to a substring of the text to be typed using index.
    typeText.innerText = textToBeTypedArr[textToBeTypedIndex].slice(0, index)
    if (isAdding) {
      // adding text
      if (index > textToBeTypedArr[textToBeTypedIndex].length) {
        // no more text to add
        isAdding = false
        //break: wait 2s before playing again
        setTimeout(function () {
          playAnim()
        }, 2000)
        return
      } else {
        // increment index by 1
        index++
      }
    } else {
      // removing text
      if (index === 0) {
        // no more text to remove
        isAdding = true
        //switch to next text in text array
        textToBeTypedIndex = (textToBeTypedIndex + 1) % textToBeTypedArr.length
      } else {
        // decrement index by 1
        index--
      }
    }
    // call itself
    playAnim()
  }, isAdding ? 120 : 60)
}
// start animation
playAnim()

See the Pen Untitled by 서근 (@seogun95) on CodePen.

텍스트가 추가될 때 커서 깜빡임 없애기

텍스트가 추가될때 동안 커서가 깜빡이지 않게 할 수도 있습니다.

.typeText::after {
  content: "|";
  /* animation: blink 1s step-end infinite; */
  animation: none;
}

.showAnim.typeText::after {
  animation: blink 1s step-end infinite;
}

그리고 자바스크립트에 아래 코드를 추가해줍니다.

function playAnim() {
    //...
      if (index > textToBeTyped.length) {
        // no more text to add
        isAdding = false
        //break: wait 2s before playing again
        // play cursor blink animation
        typeText.classList.add("showAnim")
        setTimeout(function () {
          // remove cursor blink animation
          typeText.classList.remove("showAnim")
          playAnim()
        }, 2000)
        return
    //...
}

See the Pen Untitled by 서근 (@seogun95) on CodePen.

 

읽어주셔서 감사합니다🤟

 

 


잘못된 내용이 있으면 언제든 피드백 부탁드립니다.


서근


위처럼 이미지 와 함께 댓글을 작성할 수 있습니다.