I'm a newb to development, so this may come off as a stupid question, but I figured I'd ask anyway. After all, me looking bad just makes you look better. :)

I want to change the css style on an element based on time. I've tried a few different methods and can get the time to display inside of html, but I can't use the time to trigger other events. I've put this little page together to make things simpler for me.

 <html>
 <head>
 <title>timerTest</title>
 <style type="text/css">

 #box {
    height:200px;
    width: 200px;
    background-color: red;
 }

 </style>
 </head>

 <body onload="maFucktion()">
   <div id="box">T</div>
   <script type="text/javascript">

     var box = document.getElementById('box');

     function maFucktion()
     {

       var d = new Date();

       for(i=0; i > 100; ++i)
       {
          if((d.getTime() % 1000) < 499)
        {
        box.style.backgroundColor = "blue";
        box.innerHTML = d.getTime() % 1000;
        }
      else
        {
        box.style.backgroundColor = "red";
        box.innerHTML = d.getTime() % 1000;
        }
      }
 }
 </script>
 </body>
 </html>

So, what my little brain tells me this should do is, on page load, execute maFucktion() which should initiate a for loop which:

(1)sets a new Date() (2)gets the time since january 1 1970 in milliseconds with the getTime() method (3)breaks it down to the half second with the modulus operator (4)and delivers a new background color and the division remainder of the condition based on whether the value is between 0-499 or else

I want it to change box.style.backgroundColor every half second which should end up looking like one of those silly banner ads from 1998, but I can't get it to automatically change.

I know a for loop probably isn't the best, but it should at least display a new innerHTML value for #box, right?

有帮助吗?

解决方案

You need to use setTimeout() or setInterval() to trigger an action at some time in the future. See here and here for doc.

Looping and checking the time is very, very bad in javascript because it locks up the browser from processing user events.

So to change the background color every half second, you could do this:

var isBlue = false;
var box = document.getElementById('box');
setInterval(function() {
    box.style.backgroundColor = isBlue ? "red" : "blue";
    isBlue = !isBlue;
}, 500);

You can see a working demo here: http://jsfiddle.net/jfriend00/n5Mhz/.

其他提示

What you really want to do here is use a timer. Have the timer call the function every 1/2 second:

<script type="text/javascript">

var box = document.getElementById('box');
var clrs = "#ff0000,#0000ff".split(",")
var cPos = 0;    
function flipC() {    
   box.style.backgroundColor = clrs[cPos];
   cPos = 1-cPos;
   window.setTimeout(flipC,500)    
}
flipC()

</script>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top