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

人盡茶涼 提交于 2019-11-28 07:06:01

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/

<script type="text/javascript">
function doFade() {
    $('.foo').toggleClass('fooAct');
    setTimeout(doFade, 1000);
}
$(document).ready(function(){
    doFade();
});
</script>
<style>
div {
height:200px;
background:black;   
}
.foo {
transition: opacity 2s;
-moz-transition: opacity 2s; /* Firefox 4 */
-webkit-transition: opacity 2s; /* Safari and Chrome */
-o-transition: opacity 2s; /* Opera */
opacity:0.1;
}
.fooAct {
opacity:1;
}
</style>
<div class="foo"></div>

just for imagination. You can do it with css3. I hope that can help you too. Doing this kind of things, css should be more confortable for browser performance instead of jQuery.

I have some problmes with setTimeout method. Maybe is better with "trigger":

var $element = $('.banner');
$element.bind('cusfadeOut',function() {
        $(this).fadeOut(500,function() {
                $(this).trigger('cusfadeIn');
        });
});
$element.bind('cusfadeIn',function() {
        $(this).fadeIn(1000, function() {
                $(this).trigger('cusfadeOut');
        });
});
$element.trigger('cusfadeOut');
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!