代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>日期特效</title>
<style>
* {
margin: 0;
padding: 0;
}
#date {
width: 450px;
height: 300px;
background-color: darkorange;
/* 圆角 */
border-radius: 10px;
/* 居中 */
margin: 100px auto;
}
#nowDate {
width: 450px;
height: 60px;
line-height: 60px;
/* 居中 */
text-align: center;
color: #fff;
font-size: 26px;
}
#day {
width: 200px;
height: 200px;
line-height: 200px;
background-color: orchid;
/* 居中 */
margin: 0 auto;
/* 字体居中 */
text-align: center;
color: #fff;
/* 字体加粗 */
font-weight: bold;
font-size: 60px;
}
</style>
</head>
<body>
<div id="date">
<p id="nowDate"></p>
<p id="day"></p>
</div>
<script>
// 1. 获取标签
var nowDate = document.getElementById("nowDate");
var day = document.getElementById("day");
// 2. 使用定时器 更新时间的变化
setInterval(nowNumTime,10);
// 获取当前年月日、时分秒、星期几的函数
function nowNumTime() {
var now = new Date();
var year = now.getFullYear();
var month = now.getMonth();
var d = now.getDate();
var hour = now.getHours();
var minute = now.getMinutes();
var second = now.getSeconds();
var week = now.getDay(); // 获取到的为索引,0代表星期日,1代表星期1,以此类推...
var weeks = ['星期日','星期一','星期二','星期三','星期四','星期五','星期六'];
var temp = "" + (hour > 12 ? hour - 12: hour);
if (temp === 0) {
temp = '12';
}
temp = temp + (minute < 10 ? ':0' : ':') + minute;
temp = temp + (second < 10 ? ':0' : ':') + second;
temp = temp + (hour < 12 ? 'A.M.' : 'P.M.')
temp = `${year}年${month}月${d}日 ${temp} ${weeks[week]}`
nowDate.innerHTML = temp;
day.innerHTML = d;
}
</script>
</body>
</html>
效果: