-
萧十郎
使用moment.js您可以允许输入如下:const threeMinuts = '3m'; // 3 minutesconst eightHours = '8.5 h'; // 8.5 hoursconst threeDays = '3 days'; // 3 days然后,您必须将数值与测量单位分开:const numberValue = Number(input.match(/(\d|\.|,)+/)[0]);const unit = input.match(/[a-z]+/)[0];之后您可以将持续时间传递给时刻,如下所示:const duration = moment.duration(numberValue, unit);例如。:const duration = moment.duration(8.5, 'h');
-
慕田峪4524236
因为我更喜欢纯 JS 并且没有库(开销很大),所以这里有一个简单的 JS 用于此任务适应(特别是正则表达式,例如数小时 (/([0-9]0-9?)[ ]?h/) 的数字) 随你便:function toSeconds(dd,hh,mm) { var d = parseInt(dd); var h = parseInt(hh); var m = parseInt(mm); if (isNaN(d)) d = 0; if (isNaN(h)) h = 0; if (isNaN(m)) m = 0; var t = d * 24 * 60 * 60 + h * 60 * 60 + m * 60; return t;}/* Expects 1d 11h 11m, or 1d 11h, or 11h 11m, or 11h, or 11m, or 1d returns number of seconds */function parseInput(sInput) { if (sInput== null || sInput=== '') return 0; var mrx = new RegExp(/([0-9][0-9]?)[ ]?m/); var hrx = new RegExp(/([0-9][0-9]?)[ ]?h/); var drx = new RegExp(/([0-9])[ ]?d/); var days = 0; var hours = 0; var minutes = 0; if (mrx.test(sInput)) { minutes = mrx.exec(sInput)[1]; } if (hrx.test(sInput)) { hours = hrx.exec(sInput)[1]; } if (drx.test(sInput)) { days = drx.exec(sInput)[1]; } return toSeconds(days, hours, minutes);}
-
喵喵时光机
分配每个<input> type="number"和min="0"。然后max="23"持续几个小时和max="59"几分钟。添加带有属性的隐藏输入name。如果您还没有准备好,请将所有内容包装在 a 中<form>并将其注册到"input"事件中。创建一个事件处理程序来提取和计算所有输入的值,然后将总计分配给隐藏输入。当<form>提交时,隐藏的输入值将被发送,因为它有一个name属性。顺便说一句,让用户在一个输入中输入如此多的值并不是真正好的用户体验。您应该为用户提供明确定义的字段,要求用户输入数据而不需要额外的复杂性。演示document.forms.duration.oninput = toMinutes;function toMinutes(e) { const dur = this.elements; let time; if (e.target.tagName === 'INPUT') { let d = Number(dur.days.value) * 1440; let h = Number(dur.hours.value) * 60; let m = Number(dur.minutes.value); time = d + h + m; dur.time.value = time; } console.log(dur.time.value);}:root,body { font: 400 3vw/1.45 Consolas}fieldset { width: max-content;}label,input { width: 6.5ch; display: inline-block; margin: 4px;}input { height: 3vw; line-height: 1; font: inherit; text-align: right}.as-console-wrapper { width: 40%; min-height: 100%; margin-left: 60%;} <form id='duration'> <fieldset> <legend>Duration</legend> <label for='days'>Days: </label> <input id='days' type='number' min='0' value='0'><br> <label for='hours'>Hours: </label> <input id='hours' type='number' min='0' max='23' value='0'><br> <label for='minutes'>Minutes: </label> <input id='minutes' type='number' min='0' max='59' value='0'><br> </fieldset> <input id='time' name='time' type='hidden'></form>
-
拉风的咖菲猫
首先,您创建输入<input id="time" type="time">最后,使用 javascript 将值添加到输入中document.getElementById("time").value = new Date().toTimeString().slice(0,8);