手动设置使用JS构建的计时器的时间

时间:2016-09-25 15:04:41

标签: javascript jquery html timer

我有一个用于时间跟踪的计时器。单击“开始”或“停止”时,计时器工作正常。现在,我尝试允许用户单击#time标记以手动编辑时间。一旦他们通过点击计时器并点击开始手动编辑时间,它应该从那个"时间"当他们点击停止时,它应该更新隐藏的input#counter标签以将其转换为毫秒。

我的问题是我如何允许用户手动编辑时间,以便当他们点击开始/停止时,计时器根据新时间按预期工作?例如,如果我双击时间并将其设为10:00:00并按开始它应该从10:00:00开始,否则它正在更新隐藏的输入,所以当我点击提交时它会保存更新的时间

这是小提琴:https://jsfiddle.net/4pu3x62g/

以下是HTML:

<div class="form-group timer">
    <span id="time"></span>
</div>

<div class="row">
    <div class="col-md-6 col-sm-6 col-xs-6">
        <input class="btn btn-success col-md-12 col-sm-12 col-xs-12" type="button" value="start" onclick="start();">
    </div>

    <div class="col-md-6 col-sm-12 col-xs-6">
        <input class="btn btn-danger col-md-12 col-sm-12 col-xs-12" type="button" value="stop" onclick="stop();">
    </div>
</div>

<input type="hidden" value="" id="counter" name="counter" />

这是Timer JS

var clsStopwatch = function () {

  var startAt = 0;
  var lapTime = 0;

  var now = function () {
      return (new Date()).getTime();
  };

  this.start = function () {
      startAt = startAt ? startAt : now();
  };

  this.stop = function () {
      lapTime = startAt ? lapTime + now() - startAt : lapTime;
      startAt = 0;
  };

  this.time = function () {
      return lapTime + (startAt ? now() - startAt : 0);
  };
};

var x = new clsStopwatch();
var $time;
var clocktimer;

function pad(num, size) {
  var s = "0000" + num;
  return s.substr(s.length - size);
}

function formatTime(time) {
  var h = m = s = ms = 0;
  var newTime = '';

  h = Math.floor(time / (3600 * 1000));
  time = time % (3600 * 1000);
  m = Math.floor(time / (60 * 1000));
  time = time % (60 * 1000);
  s = Math.floor(time / 1000);
  ms = time % 1000;

  newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2);
  //newTime = pad(h, 2) + ':' + pad(m, 2) + ':' + pad(s, 2) + ':' + pad(ms, 2);
  return newTime;
}

function show() {
    $time = document.getElementById('time');
    update();
}

function update() {
    $time.innerHTML = formatTime(x.time());
}

function start() {
  clocktimer = setInterval("update()", 1);
  x.start();
}

function millisecondsToHours(amountMS) {
  return amountMS / 3600000;
}

function stop() {
  x.stop();
  document.getElementById('counter').value = millisecondsToHours(x.time());
  clearInterval(clocktimer);
}

以下是使span #time可编辑的插件:

//plugin to make any element text editable
$.fn.extend({
    editable: function () {
        $(this).each(function () {
            var $el = $(this),
            $edittextbox = $('<input type="text"></input>').css('min-width', $el.width()),
            submitChanges = function () {
                if ($edittextbox.val() !== '') {
                    $el.html($edittextbox.val());
                    $el.show();
                    $el.trigger('editsubmit', [$el.html()]);
                    $(document).unbind('click', submitChanges);
                    $edittextbox.detach();
                }
            },
            tempVal;
            $edittextbox.click(function (event) {
                event.stopPropagation();
            });

            $el.dblclick(function (e) {
                tempVal = $el.html();
                $edittextbox.val(tempVal).insertBefore(this)
                .bind('keypress', function (e) {
                    var code = (e.keyCode ? e.keyCode : e.which);
                    if (code == 13) {
                        submitChanges();
                    }
                }).select();
                $el.hide();
                $(document).click(submitChanges);
            });
        });
        return this;
    }
});

以下是事件触发的地方:

//implement editable plugin
$('span#time').editable().on('editsubmit', function (event, val) {
    //Need to trigger the timer with the new val from here

});

1 个答案:

答案 0 :(得分:1)

运行此代码段,其解释清楚。

&#13;
&#13;
$(function() {

  // Some global variables
  var startTime = 0,
      elapsed   = 0,
      timerId   = 0,
      $timer    = $("h1 span");
  
  function formatTime(time) {
    var hrs = Math.floor(time / 60 / 60 / 1000),
        min = Math.floor((time - hrs*60*60*1000) / 60 / 1000),
        sec = Math.floor((time - hrs*60*60*1000 - min*60*1000) / 1000);
    
    hrs = hrs < 10 ? "0" + hrs : hrs;
    min = min < 10 ? "0" + min : min;
    sec = sec < 10 ? "0" + sec : sec;
    
    return hrs + ":" + min + ":" + sec;
  }
  
  function elapsedTimeFrom(time) {
    return formatTime(time - startTime + elapsed);
  }
  
  function showElapsed() {
    $timer.text(elapsedTimeFrom(Date.now()));
  }
  
  function startTimer() {
    // React only if timer is stopped
    startTime = startTime || Date.now();
    timerId = timerId || setInterval(showElapsed, 1000);
  }
  
  function pauseTimer() {
    // React only if timer is running
    if (timerId) {
      clearInterval(timerId);
      elapsed += Date.now() - startTime;
      startTime = 0;
      timerId = 0;
    }
  }
  
  function resetTimer() {
    clearInterval(timerId);
    $timer.text("00:00:00");
    startTime = 0;
    elapsed = 0;
    timerId = 0;
  }

  function editTimer() {
    pauseTimer();
    $timer.prop("contenteditable", true);
    $timer.css("border", "1px solid red");
  }

  function setElapsed() {
    var time = $timer.text(),
        arr  = time.split(":");
    $timer.prop("contenteditable", false);
    $timer.css("border", "1px solid black");
    elapsed = parseInt(arr[0]*60*60, 10);
    elapsed += parseInt(arr[1]*60, 10);
    elapsed += parseInt(arr[2], 10);
    elapsed *= 1000;
  }
  
  function sendTime() {
    pauseTimer();
    // Set hidden input value before send
    $("[name='time']").val(formatTime(elapsed));
  }

  $("[name='start']").click(startTimer);
  $("[name='stop']").click(pauseTimer); 
  $("[name='reset']").click(resetTimer);
  $timer.dblclick(editTimer);
  $timer.blur(setElapsed);
  $("form").submit(sendTime);
  
});
&#13;
h1, h3, form { 
  text-align: center;
  font-family: sans-serif;
}
h1 span {
  border: 1px solid black;
  padding: 5px;
}
&#13;
<h3>Double click on timer to edit time</h3>
<h1><span>00:00:00</span></h1>

<form action="#" method="post">
  <input type="button" name="start" value="Start">
  <input type="button" name="stop" value="Stop">
  <input type="button" name="reset" value="Reset">
  <input type="submit" name="action" value="Submit">
  <input type="hidden" name="time" value="00:00:00">
</form>

<h3>Multiple clicks on buttons is properly handled also</h3>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
&#13;
&#13;
&#13;