我为用户选择的时间创建倒数计时器。为此,我开发了以下功能。
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函数。
答案 0 :(得分:3)
首先使用input
从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>
答案 1 :(得分:0)
你可以这样做,请看看,如果它不起作用,请告诉我。
var selectedValue = document.getElementById("picker-dates").value;
答案 2 :(得分:-1)
使用jquery:$(&#39; #picker-dates&#39;)。val()