简体   繁体   English

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

[英]Manually set time on timer built with JS

I have a timer I am using for time tracking.我有一个用于时间跟踪的计时器。 The timer works great when I click Start or Stop.当我单击“开始”或“停止”时,计时器效果很好。 Now I am trying to allow for the user to click on the #time tag to manually edit the time.现在我试图允许用户点击#time标签来手动编辑时间。 Once they edit the time manually by clicking on the timer and click start it should start from that "time" and when they click stop it should update the hidden input#counter tag to convert that into milliseconds.一旦他们通过单击计时器手动编辑时间并单击开始,它应该从那个“时间”开始,当他们单击停止时,它应该更新隐藏的input#counter标签以将其转换为毫秒。

My Question is how do I allow the user to edit the time manually so when they click start/stop the timer works as expected based on the new time?我的问题是如何允许用户手动编辑时间,以便当他们单击开始/停止时,计时器会根据新时间按预期工作? For example, if I double click on the time and make it 10:00:00 and press start it should start from 10:00:00, otherwise it is updating the hidden input so when I click submit it saves the updated time例如,如果我双击时间并将其设为 10:00:00 并按开始,它应该从 10:00:00 开始,否则它正在更新隐藏的输入,因此当我单击提交时,它会保存更新的时间

Here is the fiddle: https://jsfiddle.net/4pu3x62g/这是小提琴: https : //jsfiddle.net/4pu3x62g/

Here is the HTML:这是 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" />

Here is the Timer JS这是定时器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);
}

Here is the plugin to make the span#time editable:这是使 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;
    }
});

Here is where the event fires:这是事件触发的地方:

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

});

Run this snippet, its self explanatory.运行这个代码片段,它的自我解释。

 $(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); });
 h1, h3, form { text-align: center; font-family: sans-serif; } h1 span { border: 1px solid black; padding: 5px; }
 <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>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM