あなたが使用することができますsetTimeout
:
function flashtext(ele,col) {
var tmpColCheck = document.getElementById( ele ).style.color,
time;
if (tmpColCheck === 'grey') {
document.getElementById( ele ).style.color = col;
time=1400;
} else {
document.getElementById( ele ).style.color = 'grey';
time=700;
}
setTimeout(function(){flashtext('flashingtext','yellow')},time);
}
flashtext('flashingtext','yellow');
デモ:http://jsfiddle.net/EfpEP/
編集:
しかし、それは少し改善することができます:
function flashtext(ele,col) {
var style = document.getElementById(ele).style;
(function main(){
var cond=style.color === 'grey';
style.color=cond?col:'grey';
setTimeout(main,cond?1400:700);
})();
}
flashtext('flashingtext','yellow');
デモ:http://jsfiddle.net/EfpEP/3/
Alnitakは、ブラウザが色を別の構文に変更できるため、色を保存するという素晴らしいアイデアを持っていました。しかし、彼のコードはdocument.getElementById
毎回呼び出しています。それから、彼の考えを取り入れて、私は最良の方法は次のとおりだと思います:
function flashtext(ele,col) {
var style = document.getElementById(ele).style,
cond=style.color === 'grey';
(function main(){
cond=!cond;
style.color=cond?col:'grey';
setTimeout(main,cond?1400:700);
})();
}
flashtext('flashingtext','yellow');
デモ:http://jsfiddle.net/EfpEP/4/
編集2:
しかし、あなたが次のようなものを使用するつもりなら
flashtext('flashingtext','yellow');
flashtext('flashingtext2','blue');
...
ブラウザがフリーズすることになります。
代わりに、
function FlashText(){
var arr=[],
cond=false,
started=false;
this.add=function(el,col){
if(typeof el==='string'){el=document.getElementById(el);}
arr.push([el.style,col]);
}
this.start=function(){
if(started){return;}
started=true;
main();
}
function main(){
cond=!cond;
for(var i=0,l=arr.length;i<l;i++){
arr[i][0].color=cond?arr[i][1]:'grey';
}
setTimeout(main,cond?1400:700);
};
}
var flash=new FlashText();
flash.add('flashingtext','yellow');
flash.add('flashingtext2','blue');
flash.start();
参照によって要素を渡すことを呼び出すこともできます: flash.add(document.getElementById('flashingtext'),'yellow')
(IDを持たない要素を含む変数がある場合があります)。
ただし、の後に要素を追加しないようにしてくださいflash.start()
。これを行うと、要素main
は呼び出されるまで(おそらく1.4秒)黒(またはデフォルトの色)になります。
デモ:http://jsfiddle.net/EfpEP/6/