瞭解如何使用兩個定時器功能在JavaScript:
setTimeout
- 在指定時間後做一次。
setInterval
- 每隔指定時間做無限次。
只需使用setInterval
替換setTimeout
:
function blink() {
var f = document.getElementById('divId');
setTimeout(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 500);
}
或者,如果你想使它真正眨眼,做到這一點,如在上述一個剛剛翻轉一次,而你需要做兩次:
function blink() {
var f = document.getElementById('divId');
setTimeout(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 500);
setTimeout(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 1000);
}
如果不是兩次,使用嵌套:
function blink() {
var f = document.getElementById('divId');
setTimeout(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
setTimeout(function() {
f.style.display = (f.style.display == 'none' ? '' : 'none');
}, 500);
}, 500);
}
查看兩個功能的計時功能和秒數。
更新
貌似OP希望有一個黃色的漸變效果,一旦頁面加載:
$(function() {
$("#fade-it").delay(150).animate({
"background-color": "#fc9"
}, 350, function() {
$("#fade-it").animate({
"background-color": "#fff"
}, 200);
});
});
* {font-family: 'Segoe UI', sans-serif; margin: 0; padding: 0; list-style: none;}
#fade-it {padding: 15px; text-align: center;}
<script src="http://code.jquery.com/jquery-2.2.4.min.js"></script>
<script src="http://code.jquery.com/ui/1.12.0/jquery-ui.min.js"></script>
<div id="fade-it">
Welcome!
</div>
注:我已經使用過jQuery和jQuery UI,我們也可以在純CSS中執行。
更新:使用純CSS動畫。
* {
font-family: 'Segoe UI', sans-serif;
margin: 0;
padding: 0;
list-style: none;
}
#fade-it {
padding: 15px;
text-align: center;
}
@-webkit-keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
@-moz-keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
@keyframes yellow-fade {
from {
background: #f96;
}
to {
background: #fff;
}
}
#fade-it {
-webkit-animation: yellow-fade 1s ease-in-out 0s;
-moz-animation: yellow-fade 1s ease-in-out 0s;
-o-animation: yellow-fade 1s ease-in-out 0s;
animation: yellow-fade 1s ease-in-out 0s;
}
<div id="fade-it">
Welcome!
</div>
我只想強調,並做出格呆在那裏。我的div消失了! – sahana
這是正確的答案。我還可以提到,如果你想再次使用setInterval,你應該把它設置爲一個變量,例如'var myInterval = setInterval(function(){....'這將允許您通過執行'clearInterval(myInterval)'來停止時間間隔。您也可以在執行之前停止超時同樣的事情作爲間隔,並執行'clearTimeout(myTimeout)' –
@sahana然後刪除第二個函數,你需要在一定時間後顯示一次,或者?請問你是否應該這樣做:'show','' hide','show'或'hide','show'? –