<!DOCTYPE html>
<html lang="zh-cn">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>循环倒计时</title>
</head>
<body>
<div id="app">
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
$(function () {
/*倒计时*/ //秒 位置 回调函数
function newCountdown(s, $_, cb) {
//秒=(时间戳)/1000
s = parseInt(s)
var this_time_countdown;
var timer = setInterval(function () {
if (!$_.length) {
return clearInterval(timer); //无dom时自动清除定时器
};
s--;
//天
var day = Math.floor(s / 24 / 3600)
//时
var hour = Math.floor((s - day * (24 * 3600)) / 3600)
//分
var minute = Math.floor((s - day * (24 * 3600) - hour * 3600) / 60)
//秒
var second = Math.floor(s - day * (24 * 3600) - hour * 3600 - minute * 60)
if (day > 0) {
this_time_countdown = day + "天" + hour + "时" + minute + "分" + second + "秒"
} else {
if (hour > 0) {
this_time_countdown = hour + "时" + minute + "分" + second + "秒"
} else {
if (minute > 0) {
this_time_countdown = minute + "分" + second + "秒"
} else {
this_time_countdown = second + "秒"
}
}
};
$_.text(this_time_countdown);
if (s == 0) {
clearInterval(timer);
if (cb && typeof (cb) === 'function') {
cb();
};
}
}, 1000);
};
//加入DOM
var timeNum = 3; //倒计时时间
var dom = '<p>倒计时:<span id="timeTipBox">' + (timeNum-1) + '秒</span></p>';
$(dom).appendTo('body');
//倒计时--start
function setTime() {
newCountdown(timeNum, $('#timeTipBox'), function () {
setTime();
});
}
//启动倒计时,防止dom没有渲染
setTimeout(() => {
setTime();
}, 0);
});
</script>
</body>
</html>
jq中动态加DOM后进行循环倒计时
最新推荐文章于 2023-08-15 14:32:00 发布