其他分享
首页 > 其他分享> > 实现倒计时功能

实现倒计时功能

作者:互联网

效果图:

 代码:

<!DOCTYPE html>
<html>
	<head>
		<meta charset="utf-8">
		<title></title>
		<style type="text/css">
			.box{
				width: 170px;
				margin: 0 auto;
				border-radius: 10px;
				text-align: center;
				background-color: rgb(0,197,205);
			}
		</style>
	</head>
	<body>
			<div class="box">
				
			<span><span id="day" >00</span>天</span>
			<strong><span id="hour">00</span>时</strong>
			<strong><span id="minute">00</span>分</strong>
			<strong><span id="second">00</span>秒</strong>
			
			</div>
			
			<script>
			function getInterval(start,end){
				//时间差 毫秒值
				var interval = end - start;
				//转换成秒 相差的总共的秒数
				interval = interval/1000 ;
				var day,hour,minute,second;
				day = Math.floor(interval/60/60/24);
				hour = Math.floor(interval/60/60%24);
				minute = Math.floor(interval/60%60);
				second = Math.floor(interval%60);
				return {
					day : day,
					hour : hour,
					minute : minute,
					second : second
				}
			}
			//倒计时
			var spanDay = document.getElementById('day');
			var spanHour = document.getElementById('hour');
			var spanMinute = document.getElementById('minute');
			var spanSecond = document.getElementById('second');
			//时间差
			var end = new Date('2022-11-22');
			setInterval(countdown,1000);
			
			countdown();
			
			function countdown(){
			
				var start = new Date();
				var obj = getInterval(start,end);
			
			
				// 给数值不够两位的补0
				obj.day =  obj.day < 10 ?'0'+obj.day : obj.day;  
				obj.hour =  obj.hour < 10 ?'0'+obj.hour : obj.hour;  
				obj.minute =  obj.minute < 10 ?'0'+obj.minute : obj.minute;  
				obj.second =  obj.second < 10 ?'0'+obj.second : obj.second ;  
				
				spanDay.innerText = obj.day;
				spanHour.innerText = obj.hour;
				spanMinute.innerText = obj.minute;
				spanSecond.innerText = obj.second;
			
			}
		</script>
	</body>
</html>

标签:功能,obj,hour,实现,倒计时,second,var,day,minute
来源: https://blog.csdn.net/qq_63606505/article/details/122159663