我们用原生的Javascript做一个小应用:实现活动的时间倒计时效果。废话不多说,我们一起来看。先看下效果图:
其实最核心的就是JS代码:
<script> window.onload = function(){ setInterval(FreeTime,1000); } function FreeTime(){ var curTime = Date.now(); var endTime = new Date("2022-10-26 16:00:00"); var allFreeSeconds = (endTime-curTime)/1000; if(allFreeSeconds>0){ var freeDay = Math.floor(allFreeSeconds/(24*60*60)); var freeHour = Math.floor(allFreeSeconds/(60*60) % 24); var freeMinute = Math.floor(allFreeSeconds/60 % 60); var freeSecond = Math.floor(allFreeSeconds%60); document.getElementById("nowTime").innerHTML = "剩余"+freeDay+"天"+freeHour+"时"+freeMinute+"分"+freeSecond+"秒"; } else{ document.getElementById("nowTime").innerHTML = "已结束"; } } </script>
我们在JS里写了个判断,如果时间超过了设置的活动时间,就会提示活动已结束。如果是在活动时间内就直接显示倒计时。
完整的DEMO也分享下:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>倒计时动画 | Web前端之家www.jiangweishan.com</title> <style> div{ text-align:center; height:100px; line-height:100px; } </style> <script> window.onload = function(){ setInterval(FreeTime,1000); } function FreeTime(){ var curTime = Date.now(); var endTime = new Date("2022-10-26 16:00:00"); var allFreeSeconds = (endTime-curTime)/1000; if(allFreeSeconds>0){ var freeDay = Math.floor(allFreeSeconds/(24*60*60)); var freeHour = Math.floor(allFreeSeconds/(60*60) % 24); var freeMinute = Math.floor(allFreeSeconds/60 % 60); var freeSecond = Math.floor(allFreeSeconds%60); document.getElementById("nowTime").innerHTML = "剩余"+freeDay+"天"+freeHour+"时"+freeMinute+"分"+freeSecond+"秒"; } else{ document.getElementById("nowTime").innerHTML = "已结束"; } } </script> </head> <body> <div> <span id="nowTime"></span> </div> </body> </html>
大家试试吧!
网友评论文明上网理性发言 已有0人参与
发表评论: