用js实现倒计时
- 发表时间: 2019-07-12
- 分类: JavaScript
- 阅读量: 623
- 作者: 七七
效果图如下:
代码奉上:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 | <!DOCTYPE html> <html lang= "en" > <head> <meta charset= "UTF-8" > <title>倒计时</title> </head> <style type= "text/css" > .time-item { width: 430px; height: 45px; margin: 0 auto; } .time-item strong { background: orange; color: #fff; line-height: 49px; font-size: 36px; font-family: Arial; padding: 0 10px; margin-right: 10px; border-radius: 5px; box-shadow: 1px 1px 3px rgba(0, 0, 0, 0.2); } .time-item > span { float: left; line-height: 49px; color: orange; font-size: 32px; margin: 0 10px; font-family: Arial, Helvetica, sans-serif; } .title { width: 300px; height: 50px; margin:200px auto 50px auto; } </style> <body> <h1 class= "title" >距离程序员节,还有</h1> <div class= "time-item" > <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> </body> <script> function $(id) { return document.getElementById(id); } //处理innerText和textContent的兼容性问题 // 设置标签之间的内容 function setInnerText(element, content) { // 判断当前浏览器是否支持 innerText if ( typeof element.innerText === 'string' ) { element.innerText = content; } else { element.textContent = content; } } // 获取两个日期的时间差 function getInterval(start, end) { // 两个日期对象,相差的毫秒数 var interval = end - start; // 求 相差的天数/小时数/分钟数/秒数 var day, hour, minute, second; // 两个日期对象,相差的秒数 // interval = interval / 1000; interval /= 1000; day = Math.round(interval / 60 / 60 / 24); hour = Math.round(interval / 60 / 60 % 24); minute = Math.round(interval / 60 % 60); second = Math.round(interval % 60); return { day: day, hour: hour, minute: minute, second: second } } // 目标时间 var endDate = new Date( '2019-10-24 0:0:0' ); // 获取span var spanDay = $( 'day' ); var spanHour = $( 'hour' ); var spanMinute = $( 'minute' ); var spanSecond = $( 'second' ); // 倒计时 function countdown() { // 计算时间差 // 当前时间 var startDate = new Date(); // 计算两个日期差 var interval = getInterval(startDate, endDate); setInnerText(spanDay, interval.day); setInnerText(spanHour, interval.hour); setInnerText(spanMinute, interval.minute); setInnerText(spanSecond, interval.second); } countdown(); setInterval(countdown, 1000); </script> </html> |
文章评论