js倒计时自定义小时分钟
需求
实现一个倒计时一小时的网页应用
代码
小时
分钟
<p class="count"></p>
<button id="start">START</button>
<script>
window.onload = function () {
// countDown();
document.querySelector("#start").addEventListener("click", () => {
function addZero(i) {
return i < 10 ? "0" + i : i + "";
}
var hour = document.querySelector("#hour");
var min = document.querySelector("#min");
var countTimeHour = parseInt(hour.value === "" ? "1" : hour.value);
var countTimeMin = parseInt(min.value === "" ? "0" : min.value);
var nowtime = new Date(); //你已知的时间
var t_s = nowtime.getTime(); //转化为时间戳毫秒数
var endtime = new Date(); //定义一个新时间
t_s = t_s + 1000 * 60 * countTimeMin; //设置新时间比旧时间多一分钟
t_s = t_s + 1000 * 60 * 60 * countTimeHour; //设置新时间比旧时间多一小时;
endtime.setTime(t_s);
// nt.setTime(t_s+1000*60*60*24);//设置新时间比旧时间多一天
countDown();
function countDown() {
var nowtime = new Date(); //你已知的时间
// var endtime = new Date("2019/03/16,17:57:00");
var lefttime = parseInt(
(endtime.getTime() - nowtime.getTime()) / 1000
);
var d = parseInt(lefttime / (24 * 60 * 60));
var h = parseInt((lefttime / (60 * 60)) % 24);
var m = parseInt((lefttime / 60) % 60);
var s = parseInt(lefttime % 60);
d = addZero(d);
h = addZero(h);
m = addZero(m);
s = addZero(s);
document.querySelector(
".count"
).innerHTML = `活动倒计时 ${d}天 ${h} 时 ${m} 分 ${s} 秒`;
if (lefttime <= 0) {
document.querySelector(".count").innerHTML = "Time Over!";
var isShow = false;
setInterval(() => {
isShow = !isShow;
if (isShow) {
document.title = "😆Time Over!";
} else {
document.title = "";
}
}, 1000);
return;
}
setTimeout(countDown, 1000);
}
});
// window.countDown = function () {
// };
};
</script>