Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
684 views
in Technique[技术] by (71.8m points)

delay - How to repeat (loop) Jquery fadein - fadeout - fadein

I am struggling with my first jQuery script. I've got a DIV on my page that is set to hide via CSS. Then, I have this script that runs to make it fade in, fade out, then fade in again:

<script type="text/javascript">
  (function($) {
    $(function() {
      $('#abovelogo').fadeIn(1000).delay(2000).fadeOut(1500).delay(2000).fadeIn(1500);
    }); 
  })(jQuery);
</script>

This part works fine. Now, my question:

How do I change it so that this script runs loops (forever) instead of just once?

Thanks in advance! -Nate

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Put your code inside a setInterval:

$(function () {
    setInterval(function () {
        $('#abovelogo').fadeIn(1000).delay(2000).fadeOut(1500).delay(2000).fadeIn(1500);
    }, 5000);
});

Since you will be running this as long as the page is active then you should do everything you can to optimize your code, for instance you can cache the selection outside of the interval:

$(function () {
    var $element = $('#abovelogo');
    setInterval(function () {
        $element.fadeIn(1000).delay(2000).fadeOut(1500).delay(2000).fadeIn(1500);
    }, 5000);
});

Docs for setInterval: https://developer.mozilla.org/en/window.setInterval

Also, instead of using .delay() you can use the callback functions in each animation to call one animation after another:

$(function () {
    var $element = $('#abovelogo');
    setInterval(function () {
        $element.fadeIn(1000, function () {
            $element.fadeOut(1500, function () {
                $element.fadeIn(1500)
            });
        });
    }, 5000);
});

Here is a demo: http://jsfiddle.net/xsATz/

You can also use setTimeout and call a function recursively:

$(function () {
    var $element = $('#abovelogo');
    function fadeInOut () {
        $element.fadeIn(1000, function () {
            $element.fadeOut(1500, function () {
                $element.fadeIn(1500, function () {
                    setTimeout(fadeInOut, 500);
                });
            });
        });
    }

    fadeInOut();
});

Here is a demo: http://jsfiddle.net/xsATz/1/


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...