한 글자씩 입력되는 애니매이션 만들기
html
<h1>abcde</h1>
<button>버튼</button>
요약
- 문자열의 글자를 일부분 떼오고, 변수에 추가시킨후에, h1 tag의 content에 넣음
- "a" -> "ab" -> "abc" -> ... -> "abcde"
let text = $("h1").text();
$("button").on("click", function () {
$("h1").text("");
typetext = "";
setTimeout(() => {
typetext = typetext + text[0];
$("h1").text(typetext);
}, 500);
setTimeout(() => {
typetext = typetext + text[1];
$("h1").text(typetext);
}, 1000);
setTimeout(() => {
typetext = typetext + text[2];
$("h1").text(typetext);
}, 1500);
setTimeout(() => {
typetext = typetext + text[3];
$("h1").text(typetext);
}, 2000);
setTimeout(() => {
typetext = typetext + text[4];
$("h1").text(typetext);
}, 2500);
});
확장성있게 코드를 수정
- 코드가 0,1,2,3,4 숫자만 다르고 나머지는 같음 -> 반복문화
- 단, 500, 1000, 1500, 2000... 반복문화 가능
- 5001, 5002, 500*3 곱하기로 분리가능하기 때문이다
- h1 tag의 content에 글자가 추가하더라도, 실행되도록 반복문 변수 i의 범위를
문자열의 길이
로 조정
$("button").on("click", function () {
$("h1").text("");
typetext = "";
for (let i = 0; i < text.length; i++) {
setTimeout(() => {
typetext = typetext + text[i];
$("h1").text(typetext);
}, 500 * i);
}
});