简体   繁体   中英

How to make text fade out

I have an HTML form, and on a button click, javascript processes it, and text appears below the button, saying "form sent". I would like to make this text fade away after a few seconds, say around five. I am using this method to write the text in the first place:

document.getElementById('sent_box').innerHTML='form sent.';

The HTML box being written to looks like this:

<div id='sent_box'></div>

with this styling:

#sent_box{
height: 20px;
margin-top: 20px;
}

How would I be able to make the text fade out after ten seconds?

Note that I need a Vanilla Javascript solution to this. NO JQuery answers, please.

Thanks for any help!

You can do this with pure JS.

I've added comments for each line of the JS so you can understand and learn for future reference.

 setTimeout(function() { // start a delay var fade = document.getElementById("fade"); // get required element fade.style.opacity = 1; // set opacity for the element to 1 var timerId = setInterval(function() { // start interval loop var opacity = fade.style.opacity; // get current opacity if (opacity == 0) { // check if its 0 yet clearInterval(timerId); // if so, exit from interval loop } else { fade.style.opacity = opacity - 0.05; // else remove 0.05 from opacity } }, 100); // run every 0.1 second }, 5000); // wait to run after 5 seconds 
 <div id="fade">Test</div> 

Here's a simpler option.

The CSS:

<style>
#objecttofade{
             color: white;
             opacity: 1;             //set opacity to 1 so it will be fully visible
             transition: all 0.25s; //you can change the duration of the transition
             }
<style>

JS:

<script> function change(){                        //assign onload or onclick
    document.getElementById('p1').style.opacity = "0";}//changes opacity to 0
</script>

Why not use css 3. Follow this link to jsfiddle for an example.

http://jsfiddle.net/nZjEL/179/

 @-webkit-keyframes fade-out {
0% { opacity: 1; -webkit-transform: scale(1);}
85% {opacity: 1; -webkit-transform: scale(1.05);}
100% {-webkit-transform: scale(.1); opacity: 0;}
}

.fade-out {
    -webkit-animation: fade-out .5s ease-in;
    -webkit-animation-fill-mode: forwards;
    -webkit-animation-iteration-count: 1;
    background-color: #000;
    width: 100px;
    height: 100px;
    opacity: 1;
}

.fade-out.one {-webkit-animation-delay: .5s;}
.fade-out.two {-webkit-animation-delay: 1.5s;}
.fade-out.three {-webkit-animation-delay: 2.5s;}
.fade-out.four {-webkit-animation-delay: 5.5s;}

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