Home  >  Article  >  Web Front-end  >  javascript实现下班倒计时效果的方法(可桌面通知)_javascript技巧

javascript实现下班倒计时效果的方法(可桌面通知)_javascript技巧

WBOY
WBOYOriginal
2016-05-16 15:50:311823browse

本文实例讲述了javascript实现下班倒计时效果的方法。分享给大家供大家参考。具体如下:

周末了,搞个下班倒计时,娱乐下。

确保下面三点:

1、非IE浏览器,较高Chrome版本,已开启HTML5桌面通知。具体设置见下面截图
2、将这个HTML放到本地Web服务器上测试,直接双击运行无法弹出桌面通知

顺带提下,这个程序很容易扩展成定时通知。

做这个东西的过程有两点比较纠结,总结下:

1、parseInt("09")返回的是0。正确做法是parseInt("09", 10),显式指定基数为十进制
2、false与"false",这个也有点小纠结,开始我这样
$("#minute").attr("readonly", "false");
但达不到效果,因为实际上readonly属性只有两个值true或false,所以如果我设置它的值为"false",那么相当于设置(非空字符串转成布尔类型为true):
$("#minute").attr("readonly", true);

更新:

修复了一些小Bug,体会到这句话”看起来很简单的东西也不是那么容易“。

运行效果如下图所示:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" 
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta name="author" content="By jxqlovejava" />
  <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
  <title>下班倒计时</title>
  <style type="text/css">
    body {
      color:#333;
      font-family:meiryo, Arial, Helvetica, sans-serif;
      font-size:12px;
      height:100%;
      margin:0 auto;
      padding:0;
      width:100%;
    }
    html,body,div,dl,dt,dd,ul,ol,li,th,td {
      margin:0;
      padding:0;
    }
    body {
      background-color: #ccc;
    }
    #counterContainer {
      width:270px;
      height:150px;
      position:absolute;
      left:50%;
      top:50%;
      margin:-75px 0 0 -135px;
      border: 1px solid #ccc;
      background-color: #fff;
    }
    #timeContainer, #toolBarContainer, #msgContainer {
      text-align: center;
    }
    #timeContainer {
      margin-top: 38px;
    }
    #toolBarContainer {
      margin-top: 15px;
    }
    .timeBox {
      width: 30px;
    }
    #minute, #second {
      text-align: center;
    }
    .highLight {
      font-weight: bold;
      color: green;
    }
    .bt {
      width: 84px;
    }
    #msg {
      visibility:hidden;
      padding-top: 10px;
    }
  </style>
</head>
<body>
  <div id="counterContainer">
    <div id="timeContainer">
      还有
      <input type="text" id="minute" class="timeBox" value="00">分 
      <input type="text" id="second" class="timeBox" value="00">秒 
      <span class="highLight">下班!</span>
    </div>
    <div id="toolBarContainer">
      <input type="button" id="setOrResetBt" class="bt" value="设定" />
      <input type="button" id="startBt" class="bt" value="开始倒计时!" />
    </div>
    <div id="msgContainer">
      <span id="msg" class="highLight">可以下班了,哦耶~~</span>
    </div>
  </div>
  <script type="text/javascript" src="jquery-1.7.1.min.js"></script>
  <script type="text/javascript">
    var minuteLeft;   // 剩下的分
    var secondLeft;   // 剩下的秒
    var totalSeconds;  // 剩下的总秒数
    var myInterval;   // 倒计时用的time interval
    var isCounting = false; // 是否正在倒计时
    var hasSetted = false; // 是否已设定完毕
    var charLimit = 2; // 分和秒都只能为2位
    // 桌面通知
    function sendDesktopNotification(title, msg) {
      if(!window.webkitNotifications || (window.webkitNotifications.checkPermission()!=0)) { // 不支持桌面通知或未授权
        alert("不好意思,你的浏览器不支持桌面通知或者你未开启!");
        return; // 不支持桌面通知
      }
      var notificationMsgBox = window.webkitNotifications.createNotification(icon="images/favicon.ico", title, msg);
      notificationMsgBox.show();
    }
    $(function() {
      // 将两位字符串转成00-59格式
      function convertToStandardFormat(timeInput) {
        var val = $(timeInput).val();
        if(val.length == 0) {
          return;
        }
        else if(val.length == 1) {
          if(isNaN(val)) {
            $(timeInput).val('0');
          }
        }
        else if(val.length == 2 || val.length == 3) {
          var intVal = parseInt(val, 10);
          if(isNaN(intVal) || intVal <= 0) {
            $(timeInput).val('00');
          }
          else {
            var firstDigit = parseInt(val[0]);
            if(firstDigit > 5) {
              firstDigit = 0;
            }
            $(timeInput).val(firstDigit+val[1]);
          }
        }
      }
      // 限制分输入框和秒输入框都只能输入两个字符且范围为00-59
      $("#minute").keyup(function(e) {
        if(e.keyCode == 37 || e.keyCode == 39) // 方向键
          return;
        convertToStandardFormat($(this));
      });
      $("#second").keyup(function(e) {
        if(e.keyCode == 37 || e.keyCode == 39) // 方向键
          return;
        convertToStandardFormat($(this));
      });
      $("#setOrResetBt").click(function() {
        if($(this).val() === "设定") {
          if(parseInt($("#minute").val(), 10) == 0 && parseInt($("#second").val(), 10) == 0) {
            alert("请设定分、秒为0到59范围内的数字!");
            return;
          }
          hasSetted = true;
          // 设置分输入框和秒输入框不可编辑
          $("#minute").attr("readonly", true);
          $("#second").attr("readonly", true);
          minuteLeft = parseInt($("#minute").val(), 10);
          secondLeft = parseInt($("#second").val(), 10);
          totalSeconds = minuteLeft*60 + secondLeft;
          // 按钮文字切换
          $(this).val("重置");
        }
        else { // 点击了重置按钮
          clearInterval(myInterval);
          isCounting = false;
          hasSetted = false;
          $("#msg").css("visibility", "hidden");
          // 设置分输入框和秒输入框可编辑
          $("#minute").attr("readonly", false);
          $("#second").attr("readonly", false);
          $("#minute").val("00");
          $("#second").val("00");
          // 按钮文字切换
          $(this).val("设定");
        }
      }); 
      $("#startBt").click(function() {
        if(!hasSetted) {
          alert("请先设定时间!")
          return;
        }
        if(!isCounting) {
          myInterval = setInterval(function() {
            totalSeconds--;
            if(secondLeft == 0 && minuteLeft > 0) {
              minuteLeft--;
              secondLeft = 59;
            }
            else {
              secondLeft--;
            }
            // 更新分秒显示
            $("#minute").val(minuteLeft > 9 &#63; minuteLeft : ('0'+minuteLeft));
            $("#second").val(secondLeft > 9 &#63; secondLeft : ('0'+secondLeft));
            if(totalSeconds==0) {  // 下班时间到了
              clearInterval(myInterval);
              $("#msg").css("visibility", "visible");
              sendDesktopNotification("下班了", "亲,下班了!\nHappy Weekend!");
            }
          }, 1000); // 每一秒钟更新一下时间
        }
        isCounting = true;
      });
    });
  </script>
</body>
</html>

希望本文所述对大家的javascript程序设计有所帮助。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn