Javascript在一个序列中动画多个DIV's

Javascript animating several DIV's in a sequence

本文关键字:DIV 动画 一个 Javascript      更新时间:2023-09-26

我想按顺序动画div,但不知道如何操作,这是我想动画

的代码
<div id="project_container">
    <div class="project_box">
        <img src="images/project.jpg">
    </div>
    <div class="project_box">
        <img src="images/project1.jpg">
    </div>
    <div class="project_box">
        <img src="images/project2.jpg">
    </div>
    <div class="project_box">
        <img src="images/project3.jpg">
    </div>
    <div class="project_box">
        <img src="images/project4.jpg">
    </div>
    <div class="project_box">
        <img src="images/project5.jpg">
    </div>
</div>

这里我们有类似的类型6div,其中名称。当动画开始时,第一个div动画和其他5个div隐藏,当第一个div动画完成时,第二个div开始动画和接下来的4个div隐藏,类似地,当第二个div动画完成时,第三个div开始动画,当最后一个div动画完成时,这些动画继续。

我会使用jQuery来做动画。查看工作演示:

小提琴示例

作为快速参考,下面是javascript代码:
var box_count = -1;
// store boxes in a variable for later reference, this increases javascript speed
var boxes = $('#project_container').children();
// initially hide all boxes
boxes.hide();

var animate_box = function(){
    // get next box
    box_count++;
    //check if boxes are left
    if(box_count < boxes.length ){ 
        //do your Animation
        $(boxes[box_count]).fadeIn({
            //call animation again once complete
            complete: animate_box
        });
    }
}
//start first animation
animate_box();

工作小提琴演示

使用RAW JavaScript可能有点困难,但如果你更喜欢使用jQuery,一个递归函数可以为你做:

$(function () {
    function show() {
        // get first hide element and show it 
        $('.project_box:not(.completed):first').show(500, function () {
            // mark it as completed
            $(this).addClass('completed');
            // show next one
            show();
        });
    }
    // invoke the function for the first time
    show();
});

我建议您使用Jquery来完成这个操作

这是Jquery动画的API文档

您可以轻松地实现如下操作:

  $('.project_box').animate({
    width: '100px'
  }, 5000, function() {
    // Animation complete.
  });

对于您的情况,要逐个动画:

var childArray = new Array();
$(". project_box").each(function(){
  childArray.push($(this));
});
runAnimation();
int count = 0;
function runAnimation(){
  childArray[0].animation({ width: '100px' }, 1000, function(){
    if(++count < childArray.length)
     runAnimation();
  });
}

PS:我没有试过,但是结构是好的,你试着遵循结构:D

这是这些问题的解,这些答案必须写成递归式

var total_div = $('.project_box').length;Var count = 0;

function do_animate(){
     if(count<total_div){
        $('.project_box').eq(count).animate({'opacity':1,'width':'320px'},{
                duration:1000,
                complete:function(){
                    count++;
                    do_animate();
                }
            });
        }       
}
do_animate();