【发布时间】:2021-10-20 23:21:27
【问题描述】:
我正在制作一个基本计时器,这是我的第一个项目之一,当您按下按钮时,代码应创建 3 个不同的变量,这些变量从各自的输入中获取值,这 3 个代表小时、分钟和秒。
发生的情况是,如果您 console.log 这 3 个变量中的任何一个,您会因为某种原因得到未定义的变量,如果您没有这些值,则整个倒计时将不起作用。
输入在 html 中设置为从 value = 0 开始,因此它应该至少返回 0,而不是未定义
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<link rel="stylesheet" href="styles.css">
</head>
<body>
<div class="title-container">
<div class="title"><h1>vamos a meditar un poco...</h1> </div>
</div>
<div class="timer-container">
<div class="screen-timer"><h2></h2></div>
<input type="number" min="0" max="60" value="0" id="hours">
<input type="number" min="0" max="60" value="0" id="minutes">
<input type="number" min="0" max="60" value="0" id="seconds">
</div>
<div class="button-container">
<button class="btn">Iniciar</button>
</div>
<script src="app.js"></script>
这里是javascript代码:
let button = document.querySelector(".btn");
let title = document.querySelector(".title");
let screenTimer = document.querySelector(".screen-timer");
//quotes
let quotes = ["OM MANI PADME HUM", "OM", "BUENOS PENSAMIENTOS, BUENAS PALABRAS, BUENAS ACCIONES", "YO FLUYO COMO EL AGUA"];
//timer start button
button.addEventListener("click", function(){
//time units
let h = document.getElementById("hours").value;
let m = document.getElementById("minutes").value;
let s = document.getElementById("seconds").value;
//title changer
let index = parseInt((Math.random() * quotes.length));
title.innerHTML = `<div class="title"><h1>${quotes[index]}</h1></div>`;
//interval for the timer
let intervalId = setInterval(timer, 1000);
//timer
function timer(){
if(m > 0 && s <= 59){
s--;
} else if(m > 0 && s == 0){
m--;
s = 59;
} else if (h > 0 && m == 0 && s == 0){
h--;
m = 59;
s = 59;
}
if (h === 0 && m === 0 && s === 0){
clearInterval(intervalId)
}
}
//show the timer on the screen
screenTimer.innerHTML = `<div class="screen-timer"><h2> ${h + ":" + m + ":" + s} </h2></div>`
console.log(h);
console.log(m);
console.log(s);
console.log(h.value);
console.log(m.value);
console.log(s.value);
});
我看到了其他解决方案,人们编写 document.getElementById(id).onClick 而不是使用 addEventListener("click", ...) 使按钮在单击时起作用,但我认为它是相同的
【问题讨论】:
-
您已经获得了
h、m和s中的值,因为您使用的是let h = document.getElementById( "hours" ).value;。 -
请编辑您的帖子并删除未使用的详细信息和文本以简化您的问题,并注意关注您的主要问题并详细解释它以帮助其他人回答您的问题。
标签: javascript timer countdown