简体   繁体   中英

Fade-in, Fade-out of text using Javascript

I am trying to make a javascript function that makes some text fade in and out.

For example, in a form the submit button would check the validity of the inputs; if they're not valid, a message is displayed for a few seconds.

I only managed to create the fade-in effect, but not fade-out: what is a simple way to implement this?

Code snippets:

CSS for the error messages:

#pwd_not_equ{
opacity:0;
transition: opacity 2s;
color:red;
}

JS function that checks if two passwords are equal:

if ($("#pass1").val() != $("#pass2").val() && $("#pass1").val().length != 0)  {

        document.getElementById("pwd_not_equ").style.opacity="1";
        return false;

    };

Error message itself is a simple p:

<p id="pwd_not_equ"> Passwords must be equal! </p>

Thanks.

Since you already have jQuery you might as well use the fadeIn and fadeOut methods:

$(element).fadeIn();
$(element).fadeOut();

Documentation: http://api.jquery.com/fadeout/

I have a little example, I hope it can help you! I am using jQuery on this one, but if its a problem for you, tell me and I will make one with pure javascript.

 $('.fadeout').click(function() { $('#target').fadeOut('normal'); }); $('.fadein').click(function() { $('#target').fadeIn('normal'); }); $('.fd-to').click(function() { $('#target').fadeTo('fast', 0.5); }); $('.fd-to1').click(function() { $('#target').fadeTo(1000, 1); }); 
 body {padding:30px;} #target { background:#dfabba; margin-bottom:15px; height:200px; padding:5px; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <!-- fadeIn, fadeOut dan fadeTo --> <button class="fadeout">FadeOut!</button> <button class="fadein">FadeIN!</button> <button class="fd-to">FadeTo 0.5</button> <button class="fd-to1">Reset</button> <div id="target"></div> 

You have not set the opacity to 0 in any of your code, this will work:

$('#pass1, #pass2').change(function() {
   if ($("#pass1").val() != $("#pass2").val() && $("#pass1").val().length != 0)  {
       $("#pwd_not_equ").css('opacity','1');
   } else $("#pwd_not_equ").css('opacity','0');
});

jquery also has toggle

http://jsfiddle.net/bdellinger/ukyvpsbf/

$('#btn').click(function(){
    $( "#pwd_not_equ" ).toggle('slow');   
});

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