Home > Web Front-end > JS Tutorial > body text

How to achieve countdown effect with javascript (desktop notification available)_javascript skills

WBOY
Release: 2016-05-16 15:50:31
Original
1834 people have browsed it

The example in this article describes the method of using JavaScript to achieve the countdown effect after get off work. Share it with everyone for your reference. The details are as follows:

It’s the weekend, let’s have a countdown to get off work for fun.

Make sure of the following three points:

1. For non-IE browsers and higher Chrome versions, HTML5 desktop notifications have been turned on. See the screenshot below for specific settings
2. Put this HTML on the local web server for testing. Double-click it to run it, but the desktop notification will not pop up

By the way, this app can be easily expanded into scheduled notifications.

There are two tangled points in the process of making this thing. To summarize:

1. parseInt("09") returns 0. The correct approach is parseInt("09", 10), explicitly specifying the base as decimal
2. False and "false", this one is a bit confusing, at first I was like this
$("#minute").attr("readonly", "false");
But the effect is not achieved, because in fact the readonly attribute only has two values, true or false, so if I set its value to "false", it is equivalent to setting (a non-empty string is converted to a Boolean type to true):
$("#minute").attr("readonly", true);

Update:

Fixed some minor bugs and realized the saying "Things that seem simple are not that easy".

The operation effect is as shown below:

<!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>

Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!