2013-02-05 222 views
0

我有一个显示和隐藏div淡入淡出循环,我正在使用一个简短的提示与互动教程。我可以让div依次循环;不过,我想在每个提示中添加一个暂停按钮,暂停循环,并具有恢复能力。如何将该功能添加到我的脚本中?如何使用fadeLoop暂停和恢复?

这里是我的JS:

$(document).ready(function(){ 
fadeLoop() 
function fadeLoop() { 

    var counter = 0, 
     divs = $('.fader').css('visibility','visible').hide(), 
     dur = 100; 

    function showDiv() { 
     $("div.fader").fadeOut(dur) // hide all divs 
      .filter(function(index) { 
       return index == counter % divs.length; 
      }) // figure out correct div to show 
      .delay(dur) // delay until fadeout is finished 
      .fadeIn(dur); // and show it 
     counter++; 
    }; // function to loop through divs and show correct div 
    showDiv(); // show first div  
    return setInterval(function() { 
     showDiv(); // show next div 
    }, 4 * 1000); // do this every 4 seconds  
}; 

$(function() { 
    var interval; 

    $("#start").click(function() { 
     if (interval == undefined){ 
      interval = fadeLoop(); 
      $(this).val("Stop"); 
     } 
     else{ 
      clearInterval(interval); 
      $(this).val("Start"); 
      interval = undefined; 
     } 
    }); 
}); 
}); 

这里是我的小提琴:Updated Fiddle

+0

对不起解决,我无法在你的小提琴中找到'#start'按钮,所以我无法测试你的功能。什么不工作? – Bergi

+0

@Bergi用一个开始按钮更新了小提琴。你可以看到,当你点击停止时,它停止循环,但它从头开始重新开始,而不是从中断的地方。 – boy

回答

1

我以一个全局变量window.i作为计数器

function fadeLoop() { 

    var divs = $('.fader').hide(), 
     dur = 200; 

    function showDiv() { 
     divs.fadeOut(dur) // hide all divs 
      .filter(function(index) { 
       return index == window.i % divs.length; 
      }) // figure out correct div to show 
      .delay(dur) // delay until fadeout is finished 
      .fadeIn(dur); // and show it 
     window.i++; 
    }; // function to loop through divs and show correct div 
    showDiv(); // show first div  
    return setInterval(function() { 
     showDiv(); // show next div 
    }, 1 * 1000); // do this every 5 seconds  
}; 

$(function() { 
    var interval; 
    window.i = 0; 

    $("#start").click(function() { 
     if (interval == undefined){ 
      interval = fadeLoop(); 
      $(this).val("Stop"); 
     } 
     else{ 
      clearInterval(interval); 
      $(this).val("Start"); 
      interval = undefined; 
     } 
    }); 
}); 
+0

优秀的作品!谢谢! – boy