如何将JavaScript计时器放在一个盒子里?

时间:2011-01-19 18:06:05

标签: javascript jquery

我有这个JavaScript代码:

<script type="text/javascript">
                function timeMsg() {
                var t=setTimeout("doRedirect()",10000);
                }
                function doRedirect() {
                window.location.replace( "http://www.codemeh.com/" );
                }
                timeMsg();
              </script>

但是我想展示一个漂浮在右上角的盒子剩下多少时间,以及我的l;一点点的JavaScript知识我不知道从哪里开始:(

有人可以帮助我吗?

3 个答案:

答案 0 :(得分:3)

(function(count) {
   setInterval(function() {
      if( count === 0) {
          window.location.href = "http://www.codemeh.com/";
      }
      else {
          document.getElementById('box_that_floats_top_right').innerHTML = 'Timeleft: ' + (count / 1000);
          count -= 1000;
      }
   }, 1000);
}(10000));

演示http://www.jsfiddle.net/4yUqL/77/

答案 1 :(得分:1)

快速解决方案:

<input id="box" type="text" size="8" />

<script>
//Init vars 
var milsec=0;
var sec=30; 
var box = document.getElementById("box");

function display() { 
    if (milsec <= 0){ 
        milsec=9;
        sec-=1;
    } 
    if (sec <= -1){ 
        milsec=0 ;
        sec+=1;
    } else { 
        milsec-=1 ;
        box.value = sec + "." + milsec;
        //call function display after 100ms
        setTimeout(function() {display();},100);
    }
} 
display();
</script>

答案 2 :(得分:0)

<script type="text/javascript" src="jquery.js"></script> 
<script type="text/javascript">

    timeLeft = 10;
    function timeMsg() {
        if(--timeLeft == 0) {
            doRedirect();
        } else {
            $("#time").val(timeLeft);
            setTimeout("timeMsg()",1000);
        }
    }
    function doRedirect() {
        window.location.replace( "http://www.codemeh.com/" );
    }
    $(document).ready(function() {
        $("#time").val(timeLeft);
        setTimeout("timeMsg()",1000);
    });
</script>
<input id="time" size="5"></input>