java script 메모
[jquery] 한글자씩 타이핑하기
그나쓰
2022. 12. 31. 22:04
한 단어, 혹은 한 문장을
한글자씩 타이핑하여 보여주기
결과
typing
px540v.csb.app
// html
<div class="wrap">
<div class="typing_txt">
<ul> //한글자씩 보여질 단어 리스트
<li>무궁화</li>
<li>꽃이</li>
<li>피었습니다</li>
</ul>
</div>
<p class="typing"></p> //타이핑이 보여질 위치
</div>
// css
* {margin:0; padding:0;}
.wrap {position:absolute; left:50%; top:50%; transform:translate(-50%, -50%); text-align:center;}
.typing_txt {display:none;}
.typing {display:inline-block; border-bottom:1px solid black; font-size:20px; font-weight:bold;}
html 과 css는 간결하게 작성하고
let typingBool = false;
let typingIndex = 0;
let liIndex = 0;
const liLength = $('.typing_txt ul li').length;
let typingTxt = $('.typing_txt ul li').eq(liIndex).text();
typingTxt = typingTxt.split(''); //한글자씩 나누기
if(typingBool == false){
typingBool = true;
var tyInt = setInterval(typing, 100);
}
function typing(){
if(typingIndex < typingTxt.length){
$('.typing').append(typingTxt[typingIndex]);
typingIndex++;
} else {
if(liIndex >= liLength - 1){
liIndex = 0;
} else {
liIndex++;
}
// 다음 단어 타이핑을 위한 세팅
typingIndex = 0;
typingBool = false;
typingTxt = $('.typing_txt ul li').eq(liIndex).text();
clearInterval(tyInt);
setTimeout(function(){
$('.typing').html('');
tyInt = setInterval(typing, 100);
}, 500); // 0.5초 후 다음 단어 타이핑
}
}
제이쿼리를 사용해서 간단하게 작성 가능 !!
var를 안쓰고 싶은데, var tyInt에서는 let 도 const도 오류가 뜨길래 var로 작성함 ...