[英]How to make text fade out
我有一個HTML表單,然后單擊按鈕,JavaScript對其進行處理,並且按鈕下方顯示了文本,表示“表單已發送”。 我想讓此文本在幾秒鍾后消失,例如大約五秒鍾。 我首先使用此方法編寫文本:
document.getElementById('sent_box').innerHTML='form sent.';
寫入的HTML框如下所示:
<div id='sent_box'></div>
具有以下樣式:
#sent_box{
height: 20px;
margin-top: 20px;
}
十秒鍾后如何使文本淡出?
請注意,我需要使用Vanilla Javascript解決方案。 請沒有JQuery答案。
謝謝你的幫助!
您可以使用純JS執行此操作。
我為JS的每一行添加了注釋,以便您理解和學習以供將來參考。
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>
這是一個更簡單的選擇。
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>
為什么不使用css3。以下示例鏈接指向jsfiddle。
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;}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.