一、HTML
<div class="main">
<div class="box">
<input type="text" value="00" class="m" /> 分钟
<input type="text" value="00" class="s" /> 秒
</div>
<button>开始倒计时</button>
</div>
二、CSS
<style>
.main {
width: 400px;
margin: 0 auto;
background: #000;
color: #fff;
display: flex;
justify-content: center;
flex-wrap: wrap;
padding: 20px;
text-align: center;
}
input {
width: 100px;
height: 30px;
font-size: 20px;
text-align: center;
outline: none;
}
button {
margin-top: 30px;
width: 50%;
height: 40px;
line-height: 40px;
background: rgb(1, 1, 158);
color: #fff;
cursor: pointer;
}
</style>
三、JS
<!-- 引入本地jquery -->
<script src="jQuery v3.6.1.js"></script>
<script>
// 获取按钮
var btn = $("button");
// 按钮的点击事件
btn.click(function () {
// 加+号可以将“数值字符串”转成 数值
var m = +$(".m")[0].value;
var s = +$(".s")[0].value;
// 如果按钮的值为"开始倒计时"执行
if (btn.text() == "开始倒计时") {
if (s == 0 && m == 0) {
} else {
btn.text("暂停倒计时");
time1 = setInterval(function () {
// 秒减一
s--;
if (s < 0) {
s = 59;
m--;
}
if (s == 0 && m == 0) {
btn.text("开始倒计时");
// 清除定时器
clearInterval(time1);
}
// 设置分/秒的value值
$(".m")[0].value = m < 10 ? "0" + m : m;
$(".s")[0].value = s < 10 ? "0" + s : s;
}, 1000);
}
} else if (btn.text() == "暂停倒计时") {
btn.text("开始倒计时");
// 清除定时器
clearInterval(time1);
}
});
</script>