使用javascript的实时表单倒数计时器

时间:2015-10-17 13:20:53

标签: javascript jquery timer

原谅我的语法/拼写

所以,我使用javascript searching about how to make a countdown timer,但我希望它在<form>,所以当用户输入一些数字(成为秒数),然后点击“开始”,计时器将启动。但是,我坚持开发脚本。

这是身体:

$('#detik').keyup(function() {
  var sec = $(this).val();
});

var display = document.querySelector('#time'),
  timer = new CountDownTimer(sec),
  timeObj = CountDownTimer.parse(sec);
format(timeObj.minutes, timeObj.seconds);

timer.onTick(format);

$('#timerb').click(function() {
  timer.start();
});

function format(minutes, seconds) {
  minutes = minutes < 10 ? "0" + minutes : minutes;
  seconds = seconds < 10 ? "0" + seconds : seconds;
  display.textContent = minutes + ':' + seconds;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/robbmj/simple-js-countdown-timer/master/countdowntimer.js"></script>


<div class="text-center">
  <h1 id="time"></h1>
</div>
<div class="text-center">
  <form id="formtimer" name="formtimer" class="form-inline" action="#" method="post">
    <input type="number" class="form-control" id="detik" placeholder="How many secs?">
    <button class="btn btn-default" type="submit" id="timerb">Start!</button>
  </form>
</div>

我的剧本出了什么问题?为什么我无法显示 00:00

1 个答案:

答案 0 :(得分:2)

看看这个:

&#13;
&#13;
$(function(){
    $('#timerb').click(function() {
        var sec     = $("#detik").val();
        var timer   = new CountDownTimer(sec);
        var timeObj = CountDownTimer.parse(sec);
        
        format(timeObj.minutes, timeObj.seconds);
        timer.onTick(format);
        timer.start();
    });

    function format(minutes, seconds) {
        minutes = minutes < 10 ? "0" + minutes : minutes;
        seconds = seconds < 10 ? "0" + seconds : seconds;
        
        var display = document.querySelector('#time');
        display.textContent = minutes + ':' + seconds;
    }
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdn.rawgit.com/robbmj/simple-js-countdown-timer/master/countdowntimer.js"></script>


<div class="text-center">
  <h1 id="time"></h1>
</div>
<div class="text-center">
  <form id="formtimer" name="formtimer" class="form-inline" action="#" method="post">
    <input type="number" class="form-control" id="detik" placeholder="How many secs?">
    <button class="btn btn-default" type="button" id="timerb">Start!</button>
  </form>
</div>
&#13;
&#13;
&#13;