Opera 中的 Javascript 计时器错误

标签 javascript opera

这是一款简单的益智游戏,使用 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 a 0 character as octal values.

...我不认为§B.1.1 - Additional Syntax - Numeric Literals适用于 parseInt

关于Opera 中的 Javascript 计时器错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20932203/

相关文章:

apache - SSE(事件源): why no more than 6 connections?

svg - Opera 中的 SVG 文本质量不佳

html - 居中的 UL 不会在 Firefox/Opera 中水平扩展(适用于 Safari、IE6/7/8)

javascript - 如何从 Rails 数据库集合中返回选定的值?

javascript - 推送时获取 Firebase UID,然后在 Java 中使用给定的 UID 再次推送

javascript - PHP、Javascript、选择和警报

firefox - CSS 媒体查询、Opera 和 Firefox 问题

javascript - 在 1 页上配置 2 个 javascript slider

javascript - 当可编辑的 div 改变其高度时附加一个类

html - 防止电话号码被转换为 Opera Mobile 上的链接