Added a timer to Animated Collapsible DIV

2019-09-06 08:40发布

问题:

I have used http://www.dynamicdrive.com/dynamicindex17/animatedcollapse.htm to make this: [link-removed].

I'm trying to find the best way for JavaScript to loop through each of the four menus in a continuous loop without any user interaction but cant think how to do this!

Also one bug which i cant work out: It remembers which menu you were on but the background image is always from the last menu on page load.

Thanks!

回答1:

setInterval((function(){
  var count=0;
  return function(){
    var f;
    switch(count++%4) {
      case 0: f='one';break;
      case 1: f='two';break;
      case 2: f='three';break;
      case 3: f='four';break;
    }
    animatedcollapse.show(f);
  };
})(),2000);

This works (i injected as is to your code and it scrolls), although could be a whole lot shorter if you gave your img elements numeric id's, like "roller_0", "roller_1", etc. then the whole switch in the middle could be left out...

I should point out that ive wrapped the function in a closure so as to avoid the use of a global variable, although it would work without that as well.

Finally, as to your question about the image being the last one viewed before reset, you can easily rectify that with an onload call to just show arbitrarily the first image, although once you've done this automatic scrolling you might not see that necessary.



回答2:

Using jQuery, you could use the trigger() method to "simulate" user interaction. This often helps to avoid duplication. E.g.:

var timer = setInterval(function(){
    var current =  $('.image:visible');
    var next = current.nextAll('.image:first').length ? current.nextAll('.image:first') : $('.image:first');
    next.previous('.header a').trigger('.click');
}, 2000); 

(Not tested.)