倒计时原生js

时间:2022-06-08 17:42:44
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>倒计时</title>
<style type="text/css">
body,div{margin:0;padding:0;font-family:"微软雅黑";font-size:16px;}
#div1{letter-spacing:3px;width:300px;height:50px;position:absolute;left:50%;top:50%;margin-left:-150px;margin-top:-50px;background:#ff6000;line-height:50px;text-align:center;}
</style>
</head>
<body>
<div id="div1">fr</div>
<script type="text/javascript">
function addZero(val){
return val<10?("0"+val):val
} function getTimer(nowTime,targetTime){ if(targetTime>nowTime){
var spanTime = targetTime.getTime()-nowTime.getTime(); //
// 总的毫秒差 =指定时间距离1970.1.1的毫秒差 -当前时间距离1970.1.1的毫秒差
var spanDay = Math.floor(spanTime/(1000*60*60*24)); // 总的毫秒数换算成天数
var aDay = spanDay*24*60*60*1000; // 天数占用的毫秒数
var spanHours = Math.floor((spanTime-aDay)/(1000*60*60)); //总的毫秒差 换算成小时
var aHours =spanHours*60*60*1000; // 小时占用的毫秒
var spanMinute = Math.floor((spanTime-aDay-aHours)/(1000*60)); //总的毫秒差换算成分钟
var aMinute = spanMinute*1000*60; // 分钟暂用的毫秒数
var spanSec = Math.floor((spanTime-aDay-aHours-aMinute)/1000); //总的毫秒差换算成秒
var str = "倒计时:"+addZero(spanDay)+"天"+addZero(spanHours)+"时"+addZero(spanMinute)+"分"+addZero(spanSec); }else{
var str="00:00:00"
} return str;
} var nowTime = new Date(); // 获取当前时间
var targetTime = new Date("2015/4/23 01:00:00"); // 获取指定时间
var oDiv =document.getElementById("div1");
oDiv.innerHTML =getTimer(nowTime,targetTime);
var timer = setInterval(function(){
var nowTime = new Date(); // 获取当前时间
var targetTime = new Date("2015/4/23 01:00:00"); // 获取指定时间
var oDiv =document.getElementById("div1");
oDiv.innerHTML=getTimer(nowTime,targetTime);
},1000)
</script>
</body>
</html>