如何让这个Javascript以不同的方式出现?

时间:2012-02-10 03:21:56

标签: javascript

所以我想做的是让下面的代码以不同的方式显示。例如,当它说0.135731974时,我希望它真的说13.5731974%,但仍然以相同的速度计数。如果你知道我的意思,请告诉我如何!

这是代码:

 <script>

 var timer;
 var stop;

 function startCount()
 {
      stop = false;
      timer = setInterval(count,1);
 }
 function stopCount()
 {
      stop = true;
 }
 function count()
 {
      if(stop == false)
          {
           var el = document.getElementById('counter');
           var currentNumber = parseFloat(el.innerHTML);
           el.innerHTML = currentNumber+0.00000003831417624521;
      }
 }
 </script>
 </head>
 <body>

 <div id="counter">0</div>

 <input type="button" value="reset" id="reset" onclick="document.getElementById('counter').innerHTML = 0;" />
 <input type="button" value="start" id="start" onclick="startCount();" />
 <input type="button" value="stop" id="stop" onclick="stopCount();" />
 </body>
 </html>

2 个答案:

答案 0 :(得分:2)

将您的count()功能更改为:

var currentNumber = 0;
function count() {
    if (!stop) {
        var el = document.getElementById('counter');
        currentNumber += 0.00000003831417624521;
        el.innerHTML = (currentNumber * 100) + "%";
    }
}

currentNumber保存在变量中而不是每次都将其解析出HTML更加容易和高效,尤其是在将其格式化为百分比值之后。

此外,您的stopCount()功能需要这样,这样您就不会同时运行多个计时器:

function stopCount() {
    stop = true;
    clearInterval(timer);
}

整个代码块可以简化并清理为:

<html>
<head>

<script>
var timer, currentNumber = 0;

function startCount() {
    if (!timer) {      
        timer = setInterval(count, 100);
    }
}

function stopCount() {
    if (timer) {
        clearInterval(timer);
        timer = null;
    }
}

function count() {
    var el = document.getElementById('counter');
    currentNumber += 0.00000003831417624521;
    el.innerHTML = (currentNumber * 100) + "%";
}

function reset() {
    currentNumber = 0;
    document.getElementById('counter').innerHTML = "0";
}

</script>
</head>
<body>

<div id="counter">0</div>

<input type="button" value="reset" id="reset" onclick="reset()" />
<input type="button" value="start" id="start" onclick="startCount();" />
<input type="button" value="stop" id="stop" onclick="stopCount();" />
</body>
</html>

答案 1 :(得分:0)

%直接放在HTML中,然后将增量值增加100倍:

<div><span id="counter">0</span>%</div>
el.innerHTML = currentNumber + 0.000003831417624521;

http://jsfiddle.net/gilly3/MJJkq/