繁体   English   中英

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

[英]Javascript how to change cell colour on timing event?

我目前正在学习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> 

如果要重复调用给定的函数(例如每秒),则应使用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
   }
}

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

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

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

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

此处查看此工作的示例。

您的ID为“ txt”的元素如何查找? 同样,您在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> 

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

因此,如果将<td class="blinkyellow">更改为<td id="blinkyellow">它将可以正常工作。

document.getElementById('blinkyellow')是,使用受支持更多的 document.getElementById('blinkyellow')语法。

如果您确实想使用jQuery,那就简单了。

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

确保下载TimersjQuery

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM