首页 > 解决方案 > 将 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 函数中。

标签: javascripthtmluser-input

解决方案


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>


推荐阅读