每秒更新document.title

时间:2019-02-22 22:54:45

标签: javascript html

<script>
window.setInterval(function(){ document.title = "site - " + msToTime();}, 1000);
function msToTime() {
  var milliseconds = parseInt((remainingTime % 1000) / 100),
    seconds = parseInt((remainingTime / 1000) % 60),
    minutes = parseInt((remainingTime / (1000 * 60)) % 60),
    hours = parseInt((remainingTime / (1000 * 60 * 60)) % 24);

  hours = (hours < 10) ? "0" + hours : hours;
  minutes = (minutes < 10) ? "0" + minutes : minutes;
  seconds = (seconds < 10) ? "0" + seconds : seconds;

  return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
}
</script>

remainingTime将使计时器中剩下多少秒(00:07:19.7)。当我将document.title更改为alert()时,它将成功地每秒发出一次警报,但是我希望选项卡标题每秒钟更新一次。我该怎么办?

1 个答案:

答案 0 :(得分:1)

您在这里!那就是你想要的?我编辑了您的代码,添加了时间功能,请进行测试!每毫秒改变一次。

P.S-如果我是我,我将删除毫秒。没有它,保持清洁

    window.setInterval(function(){ document.title = "rumseytime - " + msToTime();}, 1000);
    function msToTime() {
      var remainingTime = new Date();
      var milliseconds = remainingTime.getMilliseconds();
        seconds = remainingTime.getSeconds();
        minutes = remainingTime.getMinutes();
        hours = remainingTime.getHours();
    
      hours = (hours < 10) ? "0" + hours : hours;
      minutes = (minutes < 10) ? "0" + minutes : minutes;
      seconds = (seconds < 10) ? "0" + seconds : seconds;
    
      return hours + ":" + minutes + ":" + seconds + "." + milliseconds;
      
    }