Jquery - 在循环中对3个div运行css规则每N秒

时间:2015-07-27 23:11:04

标签: javascript jquery html css

我有3个HTML div,例如:

HTML

<div id="one" class="hide">Text one</div>
<div id="two" >Text two</div>
<div id="three" class="hide">Text three</div>

我希望Jquery每隔N秒更改一次这样的css:

JS

// First N seconds : 
$("#two").hide(); 
$("#one").show();

//Next N seconds:
$("#one").hide(); 
$("#three").show();

//Next N seconds:
$("#three").hide(); 
$("#two").show();

接下来N秒:再做一次&#34;前N秒&#34;动作,然后再循环下两个。

我已尝试过设置Interval,但不确定如何实现此功能,因为它每次都会执行一次或多次操作。

我考虑过检查css是否可以看到div,并通过它来执行操作,但是我正在寻找一种方法来执行此操作而不依赖于div的CSS来执行每N秒操作。

div可能位于页面的任何位置,因此无法使用&#34; next&#34;要到达下一个div,我需要从一个带有div ID的数组中运行它们。例如:

idArray=["one", "two", "three"];

1 个答案:

答案 0 :(得分:1)

您的代码有点误导,因为您提到的选择器具有id而不是预期的类。

您可以改为访问所有div,并使用configure:4074: checking for gcc configure:4090: found /usr/sfw/bin/gcc configure:4101: result: gcc configure:4330: checking for C compiler version configure:4339: gcc --version >&5 gcc (GCC) 3.4.3 (csl-sol210-3_4-branch+sol_rpath) Copyright (C) 2004 Free Software Foundation, Inc. This is free software; see the source for copying conditions. There is NO warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. $ echo $PATH /usr/ccs/bin:/usr/bin:/usr/sfw/bin:/usr/sbin:/usr/local/bin:/opt/SUNWspro/bin:/bin:/usr/bin:/usr/sbin:/usr/ucb:/bns/bin:/usr/openwin/bin: $ echo $LD_LIBRARY_PATH /opt/SUNWspro11/SUNWspro/prod/lib:/usr/local/lib:/usr/lib:/usr/lib/X11 setIntervaladdClassremoveClass方法的组合来解决问题。

hide

<强> Check Fiddle

<强>更新

页面上任何位置的元素。为了实现这一点,我将在所有必须显示和隐藏的元素上有一个公共类。

var $curr =  $('div').first();
// Hide all the divs
$('div').addClass('hide');
// Display the first div
$curr.removeClass('hide'); 

var interval = setInterval(function() {
    // Hide all the divs
    $('div').addClass('hide');
    if($curr) {
        $curr = $curr.next('div');
    }

    if($curr && $curr.length === 0) {
         $curr = $('div').first();   
    }
    $curr.removeClass('hide');                       
}, 500);

<强> Updated Fiddle