2

500ms ごとに異なる色でテキストを点滅させる単純な JavaScript スクリプトを作成しようとしています。このようなことを考えましたが、機能しません。テキストを単色(緑、黒、赤の3つのいずれか)で印刷するだけです。助けてくれてありがとう

<html>
<body >
<script>

var f = function() { 
var str = "Hello World";;
var d = new Date();
var n = d.getTime();
switch(n%3)
  {
  case 1:
  fontcolor="green"
  break;
  case 2:
  fontcolor="black"
  break;
  default:
  fontcolor="red"
  }
document.write(str.fontcolor(fontcolor));   
 }
setInterval(f, 500);     
</script>
</body>
</html>
4

2 に答える 2

2

このようなものを試してみてください(何が起こっているのかを理解するためにコメントを参照してください):

// Wait until the document is ready

window.onload = function()
{
    // Create the element

    var txt = document.createElement('span');

    txt.innerHTML = 'Hello World!';

    // Insert the element to the document

    document.body.appendChild(txt);

    // Alternate the colors

    var colors  = [ 'red', 'green', 'blue', 'black', 'yellow', 'pink' ];
    var current = 0;

    setInterval(function()
    {
        // Update element's style with the new color

        txt.style.color = colors[current];

        // Go to the next color

        current = (current + 1) % colors.length;

    }, 500);
};
于 2013-03-28T23:18:34.403 に答える
0

フィドルで実行したところ、うまくいくようです。500 ミリ秒ごとに発生しているように見えますが、コンピューターでの各呼び出し間の時間は、実際には 501 ミリ秒 (または 3 の他の正確な約数)、または 3 の他の約数である可能性があります。集計カウンターは、最初は 0 で、毎回 d.getTime() % 1000 を追加し、その値を % 3 にします。

var a = 0;
var f = function() { 
    var str = "Hello World";;
    var d = new Date();
    var n = d.getTime();
    a = a + (n % 1000);
    switch(a % 3) {
        case 1:
            fontcolor="green"
            break;
        case 2:
            fontcolor="black"
            break;
        default:
            fontcolor="red"
    }
    document.write(str.fontcolor(fontcolor));
}
setInterval(f, 500);
于 2013-03-28T22:57:21.753 に答える