Html部分
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title></title>
<link rel="stylesheet" type="text/css" href="css/index.css" />
<script src="js/index.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="box" οnclick="panduan()"></div>
</body>
</html>
Css部分
* {
margin: 0;
padding: 0;
}
#box{
width: 30%;
height: 300px;
margin: 100px auto;
border: solid 1px #ccc;
text-align: center;
padding-top: 100px;
}
Js部分
function panduan() {
var box = document.getElementById('box');
// 获取当前日期
var date = new Date();
// 从Date对象以四位数字返回年份
var year = date.getFullYear();
// 从 Date 对象返回月份 (0 - 11)
var month = date.getMonth() + 1;
// 返回当前月的第几天(日期)
var day = date.getDate();
// 返回 Date 对象的小时(0-23)
var hour = date.getHours();
// 返回 Date 对象的分钟(0-59)
var minute = date.getMinutes();
// 返回 Date 对象的秒数(0-59)
var second = date.getSeconds();
// 当不够两位数时,用0补齐
month = month < 10 ? '0' + month : month;
day = day < 10 ? '0' + day : day;
hour = hour < 10 ? '0' + hour : hour;
minute = minute < 10 ? '0' + minute : minute;
second = second < 10 ? '0' + second : second;
// yyyy-MM-dd HH:mm:ss 的格式
box.innerHTML = year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' +second;
}