html倒计时源码
墨初 Web前端 659阅读
有博友来问有没有前端web用的倒计时代码,下面73so博客就分享一个利用JS代码来实现倒计时的代码。
html实现倒计时的方法
下面的倒计时的代码是利用js脚本代码实现的,你可以在js代码中设置目的的日期与时间,页面在浏览器渲染完成后,会自动计算当前与目的日期时间的差,并以每秒的时间间隔进行倒计时。
html倒计时源码:
<style> #remainTime{ background-color: #f5f5f5; font-size: 16px; text-align: center; padding: 10px 20px; display: inline-block; margin: auto; } #remainTime span { color: red; font-weight: bold; margin-right: 10px; } </style> <!-- https://www.73so.com --> <body> <div id="remainTime"> 倒计时: <span id="one"></span>天 <span id="two"></span>时 <span id="three"></span>分 <span id="four"></span>秒 </div> </body> <script> (function show() { //这里设置到期的时间 var oYear = 2023 var oMonth = 5 var oDay = 28 var oHour = 20 var oMinute = 30 var oSecond = 0 var funtureDate = new Date(oYear, oMonth, oDay, oHour, oMinute, oSecond); setInterval(function () { var presentDate = new Date(); var funtureTime = funtureDate.getTime(); var presenTime = presentDate.getTime(); var allTime = funtureTime - presenTime; var allSecond = parseInt(allTime / 1000); var day = size(parseInt(allSecond / 3600 / 24)); var hour = size(parseInt(allSecond / 3600 % 24)); var minute = size(parseInt(allSecond / 60 % 60)); var second = size(parseInt(allSecond % 60)); document.getElementById('one').innerHTML = day; document.getElementById('two').innerHTML = hour; document.getElementById('three').innerHTML = minute; document.getElementById('four').innerHTML = second; }, 1000); function size(num) { return num < 10 & num >= 0 ? '0' + num : num; } })() function dateFormat(data){ var date = new Date(data); var YY = date.getFullYear() + '-'; var MM = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1) + '-'; var DD = (date.getDate() < 10 ? '0' + (date.getDate()) : date.getDate()); return YY + MM + DD; } </script>