开发者

prototype js: rotating div display using $$ for dynamic divs

开发者 https://www.devze.com 2023-03-31 16:57 出处:网络
I\'m wondering why the following code doesn\'t work, where \"banner\" is the css class of each of four different divs. The resulting page displays all images for one second, and then they all vanish.

I'm wondering why the following code doesn't work, where "banner" is the css class of each of four different divs. The resulting page displays all images for one second, and then they all vanish.

<script type="text/javascript">
    var bannerArray = new Array();
    bannerArray = $$(".banner");

    bannerArray.each(function (b) {
        b.hide();
    });
    bannerArray.each(function (b) {
        b.show();
   开发者_开发技巧     Element.hide.delay(1, b.id);
    });
</script>


delay doesn't delay all code execution. It only delays the invocation of a specific function; the rest of your code gets executed right away, while the delay is counting down in the background. So you're setting a "hide timer" for each element at the same time. Since they all have the same 1-second delay, they all fire 1 second after being set.

Try this instead

(function() { // wrap everything in a function to avoid polluting the global namespace
    var banners = $$('.banner'); // no need to create an empty array first
    banners.invoke('hide');      // no need to use each

    function showNextBanner() {
        banners.last().hide();         // hide previous banner
        banners.first().show();        // show next banner
        banners.push(banners.shift()); // first element moves to become last element
        showNextBanner.delay(1);       // set a timeout to show the next banner
    }

    showNextBanner(); // start the banner rotation/looping
}());

Here's a demo

0

精彩评论

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

关注公众号