简体   繁体   中英

JQuery fadeOut() and fadeIn() functions doesn't work

I wanna make a floating text on a page, changing between the quotes on the quotes array. And adding some effect during this change.

I have this Html code:

<body onLoad="frase1();">
    <h1 id="textslide" class="frase-topo"></h1>
</body>

And this JavaScript code:

<script>
    var quotes = [
        "Aqui vai uma frase bem bonita",
        "E aqui também vai uma frase bem bonita"
    ];
    var i = 0;

    setInterval(function () {

        $('#textslide').fadeOut('slow', function () {
            $('#textslide').html(quotes[i]);
            $('#textslide').fadeIn('slow');
        });

        if (i === quotes.length) {
            i = 0;
        }
        else {
            i++;
        }
    }, 4000);

</script>

The quotes are changing. But it's not showing the fade effect when the quotes are changing. Someone can help?

First, wrap your function in a $(document).ready() function to ensure that the DOM is loaded before running your code.

Second, change your setInterval to a setTimeout . This makes the code wait until the previous function is complete before running it again. This should give you the results that you are wanting. See the snippet below.

 $(document).ready(function () { var quotes = [ "Aqui vai uma frase bem bonita", "E aqui também vai uma frase bem bonita" ]; var i = 0; var timeOut = function () { $('#textslide').fadeOut('slow', function () { $('#textslide').html(quotes[i]); $('#textslide').fadeIn('slow'); if (i === quotes.length) { i = 0; } else { i++; } window.setTimeout(function () { timeOut(); }, 4000); }); }; timeOut(); }); 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script> <body> <h1 id="textslide" class="frase-topo"></h1> </body> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM