开发者

How to Modify setInterval Code to Trigger the Interval Action Initially

Im not an JavaScript expert but I found a script which will help me accomplish what I need, however I need a small modification on it. Here is JS code:

$('html').addClass('js');

$(function() {

  var timer = setInterval( showDiv, 4000);

  var counter = 0;

  function showDiv() {
    if (counter ==0) { counter++; return; }

    $('#div1, #div2, #div3, #div4')
      .stop()
      .hide()
      .filter( function() { return this.id.match('div' + counter); })   
      .show('fast');
开发者_开发技巧    counter == 4? counter = 0 : counter++; 

  }

});

and here is an html code:

<div id='container'>
<div id='div1' class='display' style="background-color: red;"> 
  div1
</div>

<div id='div2' class='display' style="background-color: green;"> 
  div2
</div>

<div id='div3' class='display' style="background-color: blue;"> 
  div3
</div>
<div id='div4' class='display' style="background-color: yellow;"> 
  div4
</div>
<div>

now what this script do is make first div showup 10 seconds after page opens and then close it and open next one. What I need to change is to remove that 10 seconds time interval for first div so it open with the page and leave that time interval for other divs as it is. I hope you understand what Im trying to accomplish. Thanks for help.


Simply call showdiv() manually the first time, above where you set the timer and move the counter initialization above it:

...
var counter = 1;
showDiv();
var timer = setInterval( showDiv, 4000);
...


Try the following solution:

showDiv();
var timer = setInterval(showDiv, 4000);

var counter = 1;
function showDiv(){
  $('.display').hide();
  $('#div'+counter).show();
  (counter == 4 ? counter = 1 : counter++)
}

Working example: http://jsfiddle.net/3cKJV/

You can also utilize the jQuery functions animate() or fadeIn() to apply an effect to the transition.


I would suggest that your first div is visible from the beginning using css. In your javascript do setInterval as you initially programmed. Start your counter as 1. In showDiv raise it. Drop the initial check where you return. For the rest this should work. Get back to me if it doesn't. I'll write the actual code on my pc tomorrow.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜