每500毫秒javascript使用不同颜色的flash文本

时间:2013-03-28 22:48:30

标签: javascript html web

我正在尝试创建一个简单的javascript脚本,每500毫秒闪烁一个不同颜色的文本。我想到了这样的东西,但它不起作用,它只是用单一颜色打印出来的文本(三种绿色,黑色或红色中的一种)。谢谢你的帮助

<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>

2 个答案:

答案 0 :(得分:1)

尝试这样的事情(参考评论以了解发生了什么):

// 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);
};

答案 1 :(得分:0)

我刚刚在fiddle中运行它,它似乎有效。它看起来像是每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);