javascript - 如何根据用户输入创建计数器?
问题描述
你好,我需要你的帮助。所以我在下面有这个 html 代码,我想在 div 中创建一个带有“counter”类的计数器。基本上用户将输入数字,计数器将从 0 开始到该数字并重置回 0。我不太了解 Javascript。我想像这样展示柜台:。请帮我。
<!DOCTYPE html>
<html>
<head>
<style>
.main{ width: 1000px;
height: 250px;
margin: 0 auto;
background-color: #FBAB7E;
background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%);
}
h2{
color: white;
padding-top: 45px;
text-align: center;
text-shadow: 1px 1px 2px #000000;
}
.count{
padding-left: 375px;
padding-top: 50px;
}
.counter{
background-color: gray;
margin: 0 auto;
margin-top: 50px;
width: 750px;
height: 150px;
}
p {
font-size: 75px;
text-align: center;
padding-top: 25px;
}
</style>
<body>
<div class="main">
<h2> ENTER THE COUNT FROM '1' TO '9999' </h2>
<div class="count">
<input type="number" name="number" id="value">
<button type="submit" name="submit" id="button" onclick= > <b> Enter Counter </b> </button>
</div>
</div>
<div class="counter">
<p>9 9 9 9</p>
</div>
</body>
</html>
<script>
/** HELP HERE! /***
</script>
解决方案
let timer = null; //to make a singleton timer
function startCounter() {
if (timer) return;
let timeVal = parseInt(document.getElementById('value').value);
if (timeVal > 0 && timeVal < 1000) { //validate the timer input
timer = setInterval(function () {
if (timeVal < 0) { // if the timer is less than 0, then stop it and clear it up
clearInterval(timer);
document.getElementById('counter-label').textContent = '9 9 9 9';
timer = null;
return;
}
document.getElementById('counter-label').textContent = timeVal.toString().padStart(4, '0').split('').join(' '); // format the timer label text
timeVal--;
}, 1000);
}
};
<!DOCTYPE html>
<html>
<head>
<style>
.main{ width: 1000px;
height: 250px;
margin: 0 auto;
background-color: #FBAB7E;
background-image: linear-gradient(62deg, #FBAB7E 0%, #F7CE68 100%);
}
h2{
color: white;
padding-top: 45px;
text-align: center;
text-shadow: 1px 1px 2px #000000;
}
.count{
padding-left: 375px;
padding-top: 50px;
}
.counter{
background-color: gray;
margin: 0 auto;
margin-top: 50px;
width: 750px;
height: 150px;
}
p {
font-size: 75px;
text-align: center;
padding-top: 25px;
}
</style>
<body>
<div class="main">
<h2> ENTER THE COUNT FROM '1' TO '9999' </h2>
<div class="count">
<input type="number" name="number" id="value">
<button type="submit" name="submit" id="button" onclick="startCounter()" > <b> Enter Counter </b> </button>
</div>
</div>
<div class="counter">
<p id="counter-label">9 9 9 9</p>
</div>
</body>
</html>
推荐阅读
- php - 我怎样才能得到这个变量的值?
- php - 图片上传到博客系统问题
- android - React Native PDF 签名
- mysql - Mysql返回不同数量的行
- c# - 如何在c#中获取datagridview自制列中的数据
- database - Hibernate 写入 WildFly 数据源连接的错误数据库
- c++ - 尽管我的代码是正确的,但打开 cv 异常错误
- php - 我想使用 metasploit 转储带有 autorunscript 的通话记录无法发送短信。但我没能做到
- javascript - Electron 无法打印多个 PDF 文件,错误 3221225477
- autodesk-forge - 无法使用 3-legged 访问令牌将文件上传到存储桶