这是一款简单的益智游戏,使用 html 5 拖放操作将 span 移动到正确的位置。计时器在第一次拖动时启动(函数 drag(e)),并在保留区(未显示)中没有剩余跨度时停止。
(附带问题:是否有一种标准方法可以美化我想要的 (m)m : ss 定时器输出,还是我必须继续按原样继续?)
为什么 timer() 函数在 chrome 和 firefox 中工作得很好,但秒在 Opera 中重置为 8 秒?如果我不尝试美化秒数并改用注释掉的行,它会完美地工作。
最好的问候!
var timerOn = false;
function drag(e) {
if (timerOn == false) {
timerOn = window.setInterval(function(){ timer() }, 1000);
}
...
}
function timer() {
var content = document.getElementById("timer").textContent.split(":");
if (parseInt(content[1]) == 59) {
content[0] = (parseInt(content[0]) + 1).toString();
content[1] = "00";
}
else {
var s = parseInt(content[1]) + 1;
content[1] = (s < 10 ? "0" : "") + s.toString();
//~ content[1] = s.toString();
}
document.getElementById("timer").textContent = content[0] + ":" + content[1];
}
....
<span id="timer">0:00</span>
最佳答案
因为某些浏览器扩展了 JavaScript 的 parseInt
以将前缀 0
视为“八进制”,而 08
是无效的八进制数。
在您使用 parseInt
的不同地方,给它第二个参数(要使用的 radix — 例如,数字基数 —),例如parseInt(str, 10)
。 (出于这个原因,这通常是个好主意。)
我很惊讶你仍然在最新的浏览器中发现这种行为,因为三年半前发布的 ECMAScript5 规范明确禁止扩展 parseInt
方式,如 Annex E - Additions and Changes in the 5th Edition that Introduce Incompatibilities with the 3rd Edition 中所述:
15.1.2.2: The specification of the function
parseInt
no longer allows implementations to treat Strings beginning with a0
character as octal values.
...我不认为§B.1.1 - Additional Syntax - Numeric Literals适用于 parseInt
。
关于Opera 中的 Javascript 计时器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20932203/