Javascript - 循环3函数,每个函数之间有延迟

时间:2013-10-22 16:33:41

标签: javascript html css3

请 - 没有jQuery。

功能1导致图像出现(CSS3动画)。

功能2然后向上滑动此幻灯片底部的标题(CSS3动画)。

功能3然后向下滑动标题(CSS3动画)。

然后需要重复该过程。

我的问题:如何将这些函数放在一个连续循环中,每个函数之间都有延迟。

HTML代码

<div id="slider">

        <!-- Sildes 
             img_noshow means opacity:0;display:none;
             img_show means opacity:1;
             an_movein means a fade in effect CSS3
        -->
        <img id="img_1" class='img_show' src="/images/c1.jpg" style='width:960px;'/>
        <img id="img_2" class='img_noshow' src="/images/c2.jpg" style='width:960px;'/>
        <img id="img_3" class='img_noshow' src="/images/c3.jpg" style='width:960px;'/>
        <img id="img_4" class='img_noshow' src="/images/c4.jpg" style='width:960px;'/>
        <div id="slider_caption">
        <p id="slider_p1" class="an_slideup"><a href="#one">This is the text going with the slide 1.</a></p>
        <p id="slider_p2" class="img_noshow"><a href="#one">This is the text going with the slide 2.</a></p>
        <p id="slider_p3" class="img_noshow"><a href="#one">This is the text going with the slide 3.</a></p>
        <p id="slider_p4" class="img_noshow"><a href="#one">This is the text going with the slide 4.</a></p>
        </div>
      </div>

JAVASCRIPT代码

slide = 1;//global
function nextMove(){
  slide++;
  if(slide > 4){
    slide = 1;
  }
  //img_noshow means opacity:0;display:none;
  //img_show means opacity:1;
  //an_movein means a fade in effect
  for(i=1;i<5;i++){

    document.getElementById('slider_p'+i).className = 'img_noshow';
    if(i != slide){
      document.getElementById('img_'+i).className = 'img_noshow';
    }
    else{
      document.getElementById('img_'+i).className = 'an_movein';
    }
  }
}


function nextMove2(){
  document.getElementById('slider_p'+slide).className = 'an_slideup';
}

function nextMove3(){
  document.getElementById('slider_p'+slide).className = 'an_slidedown';
}

2 个答案:

答案 0 :(得分:3)

使用每个函数末尾的setTimeout方法在延迟后开始下一个:

function nextMove(){
  //...all dat code
  window.setTimeout(nextMove2, 500);
}

function nextMove2(){
  document.getElementById('slider_p'+slide).className = 'an_slideup';
  window.setTimeout(nextMove3, 500);
}

function nextMove3(){
  document.getElementById('slider_p'+slide).className = 'an_slidedown';
  window.setTimeout(nextMove, 500);
}

答案 1 :(得分:0)

最直观的例子:

setInterval(function() {
  nextMove();
  setTimeout(function() {
    nextMove2();
    setTimeout(nextMove3, 5000)
  }, 5000);
}, 15000); 

所以每15秒开始一次循环。执行第一个功能,等待5秒,执行第二个,等待5秒,然后执行第三个功能(所以在那之后,再次等待约5秒钟。)