0

我写了一个小脚本,随机打乱一系列 div - 这可以按预期(或希望)工作。

我的问题在于实施。我希望 div 淡出,重新洗牌并再次淡入。我发现函数 moveBox() 与任何动画同时执行。我尝试将它作为回调函数调用动画中的所有元素(fadeOut、delay 和fadeIn),但始终具有相同的效果 - div 的改组和重新分配发生在动画期间,因此是可见的。

我有一个解决方案(var ts=timeOut...),它可以在隐藏 div 时发生随机播放,但我不相信这是最好的解决方案。

我想知道如何控制函数的执行顺序以及它们应该同时执行还是按顺序执行。我的代码:

<style>
    .tester{
        float:left;
        width:100px;
        height:100px;
        margin:5px;
        }
    .tester p{text-align:center;
        margin-top:20px;
    }
    .one{background-color:red;}
    .two{background-color:yellow;}
    .three{background-color:teal;}
    .four{background-color:blue;}
    .five{background-color:green;}
    .six{background-color:silver;}
</style>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript">
    jQuery(document).ready(function(){
        var anibase=jQuery(".tester").length;
        jQuery(".tester").fadeOut(1000);
        function moveBox(){
            function shuffle(){
                for (i = 0; i <= (anibase - 2); i++) {
                    mover = Math.floor(Math.random() * (anibase - i));
                    if (mover != 0) {
                        mover = mover + i;
                        jQuery(".tester:eq(" + mover + ")").insertBefore(".tester:eq(" + i + ")");
                    };
                };
            };
            jQuery(".tester").fadeOut(1500).delay(500).fadeIn(1500);
            var ts = setTimeout(shuffle,1500);
            var t=setTimeout(moveBox,5000);
        };
        moveBox();
    });

</script>
<body>
    <div class="tester one">
        <p>box 1</p>
    </div>
    <div class="tester two">
        <p>box 2</p>
    </div>
    <div class="tester three">
        <p>box 3</p>
    </div>
    <div class="tester four">
        <p>box 4</p>
    </div>
    <div class="tester five">
        <p>box 5</p>
    </div>
    <div class="tester six">
        <p>box 6</p>
    </div>
</body>

提前致谢

4

1 回答 1

0

JQuery 具有嵌套函数的能力,有效地控制了执行的顺序。

首先,尽管在这种情况下在 Javascript 中嵌套函数是有效的,但没有必要,请考虑以下代码:

<script type="text/javascript">

  jQuery(document).ready(function(){
    moveBox();  //call the function that will do the work and then setTimeout
  });



  function moveBox(){
    jQuery(".tester").fadeOut("slow",function(){
      shuffle();
      $(this).fadeIn("slow");
      return;
    });
    var t=setTimeout(moveBox,5000);
  }

  function shuffle(){
    var anibase=jQuery(".tester").length;
    for (i = 0; i <= (anibase - 2); i++) {
      mover = Math.floor(Math.random() * (anibase - i));
      if (mover != 0) {
        mover = mover + i;
        jQuery(".tester:eq(" + mover + ")").insertBefore(".tester:eq(" + i + ")");
      }
    }
  }
</script>

这里要看的重要部分是:

jQuery(".tester").fadeOut("slow",function(){
  shuffle();
  $(this).fadeIn("slow");
  return;
});

这将指示 jQuery

  1. 淡出 .tester 元素
  2. 淡出完成后执行 shuffle()
  3. 然后将元素淡入

您可以在fadeOut文档中看到更多示例,其中一些示例显示了链式事件

此外,通过将函数定义分开,它更易于阅读。

于 2011-05-08T13:19:32.830 回答