简体   繁体   中英

Fade in and fade out text at the same location

I want to write a code which can toggle two sentences fading in and fading out. But I want to toggle the sentences at the same location ie one text fades and the other starts coming in place of the first. In this case the sentences occur one below the other. Is there any way I can do this as in html content always comes one below the other.

This is the jquery script.

<script>
 $(document).ready(function(){
 $(function(){
       $("#hide1").hide();
       while(1)
      {
       $("#hide2").fadeOut(3000);
       $("#hide1").fadeIn(3000);
       $("#hide1").fadeOut(3000);
       $("#hide2").fadeIn(3000);
     }
 });
});
</script>

Html

<p id="hide1"> Hide 1 <p>
<p id="hide2"> Hide 2 <p>

Demo Try like this make the queue and animate

  $("#hide1").hide();

function hide1() {
    $("#hide2").fadeIn(3000);
    $("#hide2").fadeOut(3000, hide2);
}

function hide2() {

    $("#hide1").fadeIn(3000);
    $("#hide1").fadeOut(3000, hide1);
}
hide1();

OR Chaining

$("#hide1").hide();

function hide1() {
    $("#hide2").fadeIn(3000).fadeOut(3000, hide2);
}

function hide2() {
    $("#hide1").fadeIn(3000).fadeOut(3000, hide1);
}
hide1();

This code would react dynamically, and it does not need any changes even if you want to apply this effect for more than two p elements

$("p").hide();

function test(elem) {
    elem.fadeIn(1000, function () {
        elem.fadeOut(1000, function () {
            test(elem.next('p').length ? elem.next('p') : $('p:first'));
        });
    });
}

test($('p:first'));

DEMO

Try this:

setInterval(function () {
    $('#hide1').fadeOut(1000, function () {
        var $this = $(this);
        $this.text($this.text() == 'Hide 2' ? 'Hide 1' : 'Hide 2');
        $this.fadeIn(1000);
    });
}, 3000);

Toggle the text within the setInterval function.

Fiddle Demo

Use a single paragraph tag and toggle the text within it while you try to fade it in and out.

$(document).ready(function(){
    $(function(){
        window.setInterval(function() {
            $("#hideorshow").fadeToggle(1000, "linear", function() {
                $("#hideorshow").text($("#hideorshow").text() === "Hide 1" ? "Hide 2" : "Hide 1");
                $("#hideorshow").fadeToggle(1000, "linear");
            });            
        }, 2000);
    });
});

Also, I would suggest you use fadeToggle() instead of fadeIn() and fadeOut() .

Here is a working JSFiddle demo .

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