javascript - 将 Html 文本输入值获取到 Javascript 函数中
问题描述
我正在为用户选择的时间创建一个倒数计时器。为此,我开发了以下功能。
function countdownTimeStart(){
var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
var x = setInterval(function() {
// Get to days date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo1").innerHTML = hours + ": "
+ minutes + ": " + seconds + " ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo1").innerHTML = "EXPIRED";
}
}, 1000);
}
这工作正常。但我想从文本输入中获取用户选择的值,而不是var countDownDate = new Date("Sep 5, 2018 15:37:25").getTime();
如
<input type = "text" id = "picker-dates" value="08:30:20">
所以任何人都可以帮助我将这个输入值添加到我的 javascript 函数中。
解决方案
input
首先使用 the获取时间值getElementById
,然后用冒号拆分该值:
以获取小时、分钟和秒。有了这些值,您就可以使用setHours
在当前日期中指定的时间来设置input
.
function countdownTimeStart(){
var time = document.getElementById("picker-dates").value;
time = time.split(':');
var date = new Date();
var countDownDate = date.setHours(time[0],time[1],time[2]);
var x = setInterval(function() {
// Get to days date and time
var now = new Date().getTime();
// Find the distance between now an the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="demo"
document.getElementById("demo1").innerHTML = hours + ": "
+ minutes + ": " + seconds + " ";
// If the count down is over, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo1").innerHTML = "EXPIRED";
}
}, 1000);
}
countdownTimeStart();
<input type = "text" id = "picker-dates" value="14:30:20">
<div id='demo1'></div>
推荐阅读
- powershell - PowerShell Windows Froms:一致的 GUI
- macos - Catalina 中的 SSH 隧道以使用屏幕共享 (VNC)
- javascript - Javascript结合正则表达式模式保留正则表达式结果
- sql - 如何对放置在 2 个不同服务器中的两个不同表进行查询
- r - 循环遍历 R 中的字符串变量名
- python - 加速随机加权选择而不用在 python 中替换
- javascript - 如果 iframe 中的 div 有特定类的孩子
- fonts - 苹果设备上的谷歌字体错误
- node.js - 部署后节点应用程序中的 aws-sdk 无法启动
- html - 更改视口没有任何作用 [Blogger]