我希望使用JQuery创建文本过渡动画,并且遇到了时间问题。我环顾了其他一些线程,却无法为我要完成的工作找出正确的解决方案。这是我拥有的HTML:

<div id="t1">
    <span>T</span>
    <span>H</span>
    <span>I</span>
    <span>S</span>
</div>
<div id="t2">
    <span>T</span>
    <span>H</span>
    <span>A</span>
    <span>T</span>
</div>


JS:

function showMessage(obj, up){
    if(dir){
        $(obj).children().each(function(i, el) {
            setTimeout(function() {
                $(el).animate({
                    'opacity': 1.0,
                    'top': '0px'
                }, 450);
            }, 500 + (i * 150));
        });
    } else {
        $(obj).children().each(function(i, el) {
            setTimeout(function() {
                $(el).animate({
                    'opacity': 0,
                    'top': '-30px'
                }, 450);
            }, 3000 + (i * 150));
        });
    }
}
showMessage("#t1", true);
showMessage("#t1", false);
showMessage("#t2", true);
showMessage("#t2", false);


THISTHAT同时显示。我怎样才能使第二个显示直到第一个完全消失?

演示:jsfiddle

最佳答案

你可以把它们拴在一起吗?

showMessage("#t1", true, function(){
  showMessage("#t1", false, function(){
    showMessage("#t2", true, function(){
       showMessage("#t2", false, function(){});
    });
  });
});


然后在showMessage中包含计数器以检查是否已显示所有跨度

    function showMessage(obj, up, callback){
    var counter = 1;
    var numberOfChildren = $(obj).children().size();
    if(up){
        $(obj).children().each(function(i, el) {
            setTimeout(function() {
                $(el).animate({
                    'opacity': 1.0,
                    'top': '0px'
                }, 450, function(){
                counter++;
                console.log(counter);
                if ( counter == numberOfChildren )
                {
                    callback();
                }
            });
            }, 500 + (i * 150));
        });
    }
    else {
        $(obj).children().each(function(i, el) {
            setTimeout(function() {
                $(el).animate({
                    'opacity': 0,
                    'top': '-30px'
                }, 450, function(){
                counter++;
                console.log(counter);
                if ( counter == numberOfChildren )
                {
                    callback();
                }
            });
            }, 3000 + (i * 150));
        });
    }
}
$(function() {
   showMessage(".dev", true, function(){
    showMessage(".dev", false, function(){
      showMessage(".dev2", true, function(){
         showMessage(".dev2", false, function(){});
      });
    });
  });
});


dir更新为up

10-07 14:50