使用 jQuery 一个接一个地切换 DOM 元素

Toggle DOM elements one after the other using jQuery

本文关键字:一个 DOM 元素 jQuery 使用      更新时间:2023-09-26

我有以下代码:

<div id="quotes">
    <p>"Quote 1."</p>
    <p>"Quote2!"</p>
    <p>"Quote3"</p>
    <p>"Etc"</p>
</div>

有没有一种简单的方法可以循环浏览每个报价,因此显示报价 1,然后淡出以显示报价 2! 等等,或者我需要使用插件吗?

$('#quotes p').each(function(index){
    $(this).delay(index * 1000).fadeIn().fadeOut();
});

或者像这样:

$('#quotes p').hide().each(function(index){
    $(this).delay(index * 1600).fadeIn().delay(750).fadeOut();
});​

现场演示

  1. 将 Q2、Q3 等的可见性保持为"隐藏"。
  2. 延迟显示第一个报价的时间,然后在回调时,您可以切换第一个和第二个报价的可见性。在此流回调中重复延迟和回调。
 $('#quotes').find('p').hide();   
 $('#quotes').find('p').each(function(i){
        $(this).prev().fadeOut('slow');
        $(this).fadeIn('slow');
    });

另一种选择是使用插件。 jQuery 循环插件很棒,设置起来非常简单:

它变成了一个单行:$('#quotes').cycle()

演示:http://jsfiddle.net/lucuma/HsWrC/1/

循环插件:http://jquery.malsup.com/cycle/

参考(控制时间间隔、动画类型等(:http://jquery.malsup.com/cycle/options.html