<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <!-- 从效果中可以看出: 需要在页面中有4个标签,其中分别放日时分秒,这4个数字不停在变化 - 每隔1s就变一次 需要在页面中放上着4个标签 --> 距离过年倒计时:<span>0</span> 天 <span>0</span> 时 <span>0</span> 分 <span>0</span> 秒 </body> <script> //将过年的时间距离现在有多少天、时分秒计算出来 - 放进标签中 var date = new Date() var year = date.getFullYear() var guonian = +new Date(year+1 + '-1-1') var spans = document.querySelectorAll('span') jisuan() function jisuan(){ //当前时间戳 var now = +new Date() //用过年时间减去当前时间戳获取到时间差 var diff = guonian - now; var arr = [] var day = parseInt(diff/1000/60/60/24) var hour = parseInt(diff/1000/60/60)%24 var minute = parseInt(diff/1000/60)%60 var second = parseInt(diff/1000)%60 arr.push(day,hour,minute,second) arr.forEach(function(v,i){ spans[i].innerText = v }) } //定时器会在1s后执行 setInterval(jisuan,1000) </script> </html>
效果图: