Javascript如何在计时事件中更改单元格颜色?

时间:2011-06-23 15:06:51

标签: javascript html html-table

我目前正在学习JavaScript,我希望在基于时间的事件中让一个单元格闪烁黄色,似乎JavaScript每次都会失败:

document.all.blinkyellow.bgColor = "yellow";

当我的计时器达到5时,它就停止了我猜它在上面的代码行上失败了,因为当我删除它时,计时器继续无限。

完整的JavaScript下面是相关的html。我想知道如何在不使用JavaScript库的情况下正确编辑单元格bg颜色,如果可能的话。

这纯粹是因为我可以学习JavaScript作为一个整体,而不是使用库,当我需要修改或插件时无法理解库。

使用Javascript:

var count=0;
var time;
var timer_is_on=0;
setTimeout(doIt, 3000);

function timedCount()
{
    if(count == 6){    

    document.all.blinkyellow.bgColor = "yellow";

    }
document.getElementById('txt').value=count;

count=count+1;
time=setTimeout("timedCount()",1000);

}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }

}

HTML:

<table> 
 <tbody> 
  <tr> 
   <td>Col 1</td> 
   <td>Col 2</td> 
   <td>Col 3</td>
   <td>Col 3</td>
  </tr> 
  <tr> 
   <td class="blinkyellow">Col 1</td> 
   <td>Col 2</td> 
   <td>Col 3</td>
   <td>Col 3</td>   
  </tr> 
  <tr> 
   <td>Col 1</td> 
   <td>Col 2</td> 
   <td>Col 3</td>
   <td>Col 3</td>   
  </tr>
  <tr> 
   <td>Col 1</td> 
   <td>Col 2</td> 
   <td>Col 3</td>
   <td>Col 3</td>
  </tr> 
 </tbody> 
</table> 

5 个答案:

答案 0 :(得分:2)

当您希望重复调用给定函数时,例如每秒, 你应该使用window.setInterval(code_or_function, milliseconds)方法:

var count = 0;
var interval = setInterval(timedCount, 1000);

function timedCount() {
   count++;
   document.getElementById("txt").value = count;
   if (count == 6) {
       document.getElementById("blinkyellow").style.backgroundColor = "yellow";
       window.clearInterval(interval);  // Stops the timer
   }
}

答案 1 :(得分:1)

要按类获取一组元素,请使用getElementsByClassName函数:

var elements = document.getElementsByClassName("blinkYellow");

然后,您可以使用style.backgroundColor循环遍历该组元素并将样式应用于它们:

for(var i = 0; i < elements.length; i++) {
    elements[i].style.backgroundColor = "yellow";
}

查看此工作的示例here

答案 2 :(得分:1)

你怎么用“txt”的id来寻找和元素?你也在你的setTimeout(doIt,3000)中调用doIt,你可能想把它改成setTimeout(“timedCount();”,3000);

另外document.all仅限IE(非常重要)!

var count=0;
var time;
var timer_is_on=0;
setTimeout("timedCount();", 3000);

function timedCount()
{
    if(count == 6){    

    document.getElementById('blinkyellow').style.backgroundColor = "yellow";

    }

count=count+1;
time=setTimeout("timedCount()",1000);

}

function doTimer()
{
if (!timer_is_on)
  {
  timer_is_on=1;
  timedCount();
  }

}

记得将td上的类改为像这样的id

<td id="blinkyellow">Col 1</td> 

答案 3 :(得分:1)

document.all.foo语法按id而不是class获取元素。

如果您将<td class="blinkyellow">更改为<td id="blinkyellow">,那么它就会有用。

或者更好的是,使用more supported document.getElementById('blinkyellow')语法。

答案 4 :(得分:0)

如果您确实想使用jQuery,那么它就是......

$(document).ready(
    function() 
    {
        $(this).oneTime(
            3000, 
            function() 
            {
                $('.blinkyellow').css('background-color', 'yellow');
            }
        );
    }
);

请务必下载TimersjQuery