JavaScript-倒计时效果
1 <!DOCTYPE html> 2 <html lang="en"> 3 <head> 4 <meta charset="UTF-8"> 5 <meta name="viewport" content="width=device-width, initial-scale=1.0"> 6 <meta http-equiv="X-UA-Compatible" content="ie=edge"> 7 <title>倒计时</title> 8 <style>.time-item { 9 width: 450px; 10 height: 45px; 11 margin: 0 auto; 12 } 13 14 .time-item strong { 15 background: orange; 16 color: #fff; 17 line-height: 49px; 18 font-size: 36px; 19 font-family: Arial; 20 padding: 0 10px; 21 margin-right: 10px; 22 border-radius: 5px; 23 box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2); 24 } 25 26 .time-item > span { 27 float: left; 28 line-height: 49px; 29 color: orange; 30 font-size: 32px; 31 margin: 0 10px; 32 font-family: Arial, Helvetica, sans-serif; 33 } 34 .title { 35 width: 260px; 36 height: 50px; 37 margin:200px auto 50px auto; 38 }</style> 39 </head> 40 <body onload="leftTimer()"> 41 <h1 class="title">距离光棍节,还有</h1> 42 43 <div class="time-item" > 44 <span><span id="day"></span>天</span> 45 <strong><span id="hour"></span>时</strong> 46 <strong><span id="minute"></span>分</strong> 47 <strong><span id="second"></span>秒</strong> 48 </div> 49 <script type="text/javascript"> 50 function leftTimer(year,month,day,hour,minute,second){ 51 52 // 参数monthIndex 是从“0”开始计算的,这就意味着一月份为“0”,十二月份为“11” 53 //以一个函数的形式来调用 Date 对象(即不使用 new 操作符)会返回一个代表当前日期和时间的字符串。 54 var leftTime = (new Date(year,month-1,day,hour,minute,second)) - (new Date()); //计算剩余的毫秒数 55 56 //parseInt解析一个字符串,返回整数 57 var days = parseInt(leftTime / 1000 / 60 / 60 / 24 , 10); 58 var hours = parseInt(leftTime / 1000 / 60 / 60 % 24 , 10); 59 var minutes = parseInt(leftTime / 1000 / 60 % 60, 10); 60 var seconds = parseInt(leftTime / 1000 % 60, 10); 61 62 //不足10的前面加上0 63 days = checkTime(days); 64 hours = checkTime(hours); 65 minutes = checkTime(minutes); 66 seconds = checkTime(seconds); 67 68 // 设置计时器 69 setInterval("leftTimer(2019,11,11,11,11,11)",1000); 70 71 //将时间加到文中 72 document.getElementById('day').innerHTML = days; 73 document.getElementById('hour').innerHTML = hours; 74 document.getElementById('minute').innerHTML = minutes; 75 document.getElementById('second').innerHTML = seconds; 76 } 77 function checkTime(i){ //将0-9的数字前面加上0 78 if(i<10) 79 { 80 i = "0" + i; 81 } 82 return i; 83 } 84 85 </script> 86 </body> 87 </html>