2017-01-08 2 views
0

배열의 문자열로 텍스트 페이드 인/페이드 아웃 효과를 통해 순환을 이루려고합니다. 예를 들어, span 태그 안에 초기 텍스트 ("Los Angeles")로 시작합니다. 이 텍스트를 문자열 "로스 앤젤레스"에서 "새크라멘토"로 바꿔 가며, 타이밍 기능으로 달성하려고하는 애니메이션과 지연을 페이드 인으로하고 싶습니다. 나는 순환하고자하는 문자열을 저장하는 배열을 정의하고있다. 문제는 배열의 첫 번째 요소에서 마지막 요소로 문자열을 변경할 수 있다는 것입니다. 사이의 요소는 샌프란시스코와 버클리처럼 for 루프에서 무시됩니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 감사. 어떤 도움을 주셔서 감사합니다. 여기에 지금까지 무엇을 가지고 있습니다 : 여러 setTimeout를 생성되지만,텍스트 추가 및 순환 효과

<div id="fly" class="container-fluid section text-center"> 
    <h1 id="intro-txt">Go from <br> <span id="dest1" style="color: #b9b7b7;">Los Angeles</span> to <span id="dest2" style="color: #b9b7b7;">Las Vegas</span> <br> with no hassle.</h1> 
    <script> 

    var from = ["San Francisco", "Berkeley", "Place3"]; 
    var to = ["Sacramento", "New Mexico", "Place3"]; 
    var total = from.length; 
    var index = 0; 

    $(document).ready(function(){ 
    for(index; index < total; index++){ 
     var fromLoc = from[index]; 
     var toLoc = to[index]; 


     var textScroll = function(){ 
     var start = $("#dest1") 
     $("#dest1").fadeOut(function() { 
      $(this).text(fromLoc).fadeIn(); 

     }); 
     $("#dest2").fadeOut(function() { 
      $(this).text(toLoc).fadeIn(); 
     });    
     } 
     setTimeout(textScroll, 2000); 
    } 
    }); 
    </script>  

답변

1

모두 실행이에서 거의 동시에 것이다.

루프의 인덱스를 지속 시간 배율로 사용하여 시간 오프셋을 만듭니다. 또한 함수가 실행되기 전에 index의 값이 최대 값이 될 것이므로 클로저가 필요합니다. 이것은 잘 작동 JavaScript closure inside loops – simple practical example

var textScroll = function(fromLoc, toLoc) { 
    var start = $("#dest1") 
    $("#dest1").fadeOut(function() { 
    $(this).text(fromLoc).fadeIn(); 

    }); 
} 
$.each(from, function(index, fromLoc) { 
    var toLoc = to[index]; 
    setTimeout(function() { 
    textScroll(fromLoc, toLoc); 
    }, index * 4000); 
}) 
+0

하세요! 감사. 많이 배웠습니다. –

+0

도움이된다면, 대답을 수락 해 주시기 바랍니다 – charlietfl

+0

죄송합니다! –

0

var from = ["San Francisco", "Berkeley", "Place3"]; 
 
var to = ["Sacramento", "New Mexico", "Place3"]; 
 
var total = from.length; 
 
var i = 0; 
 
setInterval(function(){ 
 
    $("#dest1").fadeOut(1000,function(){$(this).text(from[i])}).fadeIn(1000); 
 
    $("#dest2").fadeOut(1000,function(){$(this).text(to[i])}).fadeIn(1000); 
 
    if (i >= total-1) i = 0; 
 
    else i++; 
 
},2200);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> 
 
<div id="fly" class="container-fluid section text-center"> 
 
    <h1 id="intro-txt">Go from <br> <span id="dest1" style="color: #b9b7b7;">Los Angeles</span> to <span id="dest2" style="color: #b9b7b7;">Las Vegas</span> <br> with no hassle.</h1> 
 
</div>