前言
用js实现页面时钟的显示或倒计时的显示。
一、显示当前时间
实现效果如下:
1.js
代码如下(示例):
$(function () {
showCurrentDate();
});
function showCurrentDate() {
var now = new Date();
var year = now.getFullYear(); //得到年份
var month = now.getMonth();//得到月份
var date = now.getDate();//得到日期
var day = now.getDay();//得到周几
var hour = now.getHours();//得到小时
var minu = now.getMinutes();//得到分钟
var sec = now.getSeconds();//得到秒
var MS = now.getMilliseconds();//获取毫秒
var week;
month = month + 1;
if (month < 10) month = "0" + month;
if (date < 10) date = "0" + date;
if (hour < 10) hour = "0" + hour;
if (minu < 10) minu = "0" + minu;
if (sec < 10) sec = "0" + sec;
if (MS < 100)MS = "0" + MS;
var arr_week = new Array("星期日", "星期一", "星期二", "星期三", "星期四", "星期五", "星期六");
week = arr_week[day];
var hour1 = hour.toString().substring(0,1);
var hour2 = hour.toString().substring(1,2);
$("#hour1").html(hour1);
$("#hour2").html(hour2);
var minu1 = minu.toString().substring(0,1);
var minu2 = minu.toString().substring(1,2);
$("#minu1").html(minu1);
$("#minu2").html(minu2);
var sec1 = sec.toString().substring(0,1);
var sec2 = sec.toString().substring(1,2);
$("#sec1").html(sec1);
$("#sec2").html(sec2);
var day = "";
var time = "";
day = year + "-" + month + "-" + date ;
$("#time").html(day);
time = + " " + hour + ":" + minu + ":" + sec;
$("#currentDate").html(time);
var timer = setTimeout("showCurrentDate()", 1000);
}
2.div
代码如下(示例):
<div>
<p id="time" style="font-size: 50px;font-weight: bold"></p>
<span id="hour1"></span>
<span id="hour2"></span>
<img src="images/maohao.png">
<span id="minu1"></span>
<span id="minu2"></span>
<img src="images/maohao.png">
<span id="sec1"></span>
<span id="sec2"></span>
</div>
二、显示倒计时
前台获取后台设置的时间,显示倒计时
实现效果如下:
1.js
代码如下(示例):
$(function () {
djs();
});
function djs() {
var openDate = "2021-04-23";
var openDate = openDate.split("-");
var year = openDate[0];
var month = openDate[1]-1;
var day = openDate[2];
var hour = "09";
var minute = "30";
//计算剩余的毫秒数
var leftTime = (new Date(year,month,day,hour,minute,00)) - (new Date());
if(leftTime<0){
$("#djsshow").html("开始!");
$("#djs").css("display","none");
}else{
var days = parseInt(leftTime / 1000 / 60 / 60 / 24 , 10); //计算剩余的天数
var hours = parseInt(leftTime / 1000 / 60 / 60 % 24 , 10); //计算剩余的小时
var minutes = parseInt(leftTime / 1000 / 60 % 60, 10);//计算剩余的分钟
var seconds = parseInt(leftTime / 1000 % 60, 10);//计算剩余的秒数
if (hours < 10) hours = "0" + hours;
if (minutes < 10) minutes = "0" + minutes;
if (seconds < 10) seconds = "0" + seconds;
$("#djsshow").html("距开标还有:");
var time = days+"天" + hours+"小时" + minutes+"分"+seconds+"秒";
$("#djs").html(time);
}
setTimeout("djs()", 1000);
}
2.div
代码如下(示例):
<div>
<p id="djsshow" style="font-size: 50px;font-weight: bold"></p>
<div id="djs"></div>
</div>