채택완료

스트립트 타이핑 효과 질문

2021-04-02 (금) 10:36:29 3,638
Copy
<div class="boxed_inner">
    <p class="slogan-txt">
    가나다라마바사
    </p>
    <p class="slogan-txt">
    아자차카타파하
    </p>
    <p class="slogan">
    </p>
<p class="cover"></p>
</div>

 

<script>

var typingBool = false; 
var typingIdx=0; 
var typingTxt = $(".slogan-txt").text(); // 타이핑될 텍스트를 가져온다 
typingTxt=typingTxt.split(""); // 한글자씩 자른다. 
if(typingBool==false){ // 타이핑이 진행되지 않았다면 
   typingBool=true; 
   
   var tyInt = setInterval(typing,100); // 반복동작 
 } 
 
 function typing(){ 
   if(typingIdx<typingTxt.length){ // 타이핑될 텍스트 길이만큼 반복 
     $(".slogan").append(typingTxt[typingIdx]); // 한글자씩 이어준다. 
     typingIdx++; 
   } else{ 
     clearInterval(tyInt); //끝나면 반복종료 
   } 
 }
</script>

이렇게 있을 때 위에 글자들이 줄바꿈이 안되고 한줄로 쭉 이어지네요

줄바꿈할 수 있는 방법이 있을까요?

답변 2개 / 댓글 2개

채택된 답변
+20 포인트

$(".slogan-txt") 에 문자열이 추가되는걸 기준으로 수정해봤습니다.

<script>

var typingBool = false; 

var typingIdx=0; 

var typingTxt = ""; 

for (var i=0; i< $(".slogan-txt").length; i++) {

    var txt = $(".slogan-txt").eq(i).text().trim();

    typingTxt += (typingTxt != "")? "\n" : "";

    typingTxt += txt;

}

typingTxt=typingTxt.split(""); // 한글자씩 자른다. 

if(typingBool==false){ // 타이핑이 진행되지 않았다면 

   typingBool=true; 

   var tyInt = setInterval(typing,100); // 반복동작 

 } 

 function typing(){ 

   if(typingIdx<typingTxt.length){ // 타이핑될 텍스트 길이만큼 반복 

     if (typingTxt[typingIdx] == "\n") {

        $(".slogan").append("<br>");

     } else {

        $(".slogan").append(typingTxt[typingIdx]); // 한글자씩 이어준다. 

     }

     typingIdx++; 

   } else{ 

     clearInterval(tyInt); //끝나면 반복종료 

   } 

 }

</script>

답변에 대한 댓글 1개

와 진짜 감사합니다 너무 감사해요 ㅠㅠ

원하는 위치에 개행태그 넣으면 될거 같습니다.

function typing(){
    if(typingIdx<typingTxt.length){ // 타이핑될 텍스트 길이만큼 반복
        $(".slogan").append(typingTxt[typingIdx]); // 한글자씩 이어준다.
        if(typingIdx == 22){
            $(".slogan").append('<br/>');
        }
        typingIdx++;
    } else{
        clearInterval(tyInt); //끝나면 반복종료
    }
}

답변에 대한 댓글 1개

너무 감사합니다 ㅠㅠ 진짜 감사합니다

답변을 작성하려면 로그인이 필요합니다.