目录
1、封装时间函数
2、在页面写一个div标签,用来存放时间
3、获取div标签,开启定时器,时间为1000ms
4、先调用时间函数,防止页面加载延迟,再在定时器里调用
完整代码
效果图
1、封装时间函数
function getTime() {
let date = new Date()//获取当前日期
let year = date.getFullYear()//获取年
year = year < 10 ? '0' + year : year
let month = date.getMonth() + 1//获取月,月份要比实际月份小1,所以要加1
month = month < 10 ? '0' + month : month
let day = date.getDate()//获取日
day = day < 10 ? '0' + day : day
let hour = date.getHours()//获取时
hour = hour < 10 ? '0' + hour : hour
let minute = date.getMinutes()//获取分
minute = minute < 10 ? '0' + minute : minute
let second = date.getSeconds()//获取秒
second = second < 10 ? '0' + second : second
return `${year}年${month}月${day}日${hour}时${minute}分 ${second}秒`
}
2、在页面写一个div标签,用来存放时间
<div></div>
3、获取div标签,开启定时器,时间为1000ms
let div = document.querySelector('div')
4、先调用时间函数,防止页面加载延迟,再在定时器里调用
div.innerHTML = getTime()
setInterval(function () {
div.innerHTML = getTime()
}, 1000)
完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
div {
width: 350px;
height: 50px;
border: 1px solid red;
text-align: center;
color: white;
font-size: 20px;
font-weight: 700;
background-color: darkorange;
padding-top: 15px;
}
</style>
</head>
<div></div>
<body>
<script>
function getTime() {
let date = new Date()//获取当前日期
let year = date.getFullYear()//获取年
year = year < 10 ? '0' + year : year
let month = date.getMonth() + 1//获取月,月份要比实际月份小1,所以要加1
month = month < 10 ? '0' + month : month
let day = date.getDate()//获取日
day = day < 10 ? '0' + day : day
let hour = date.getHours()//获取时
hour = hour < 10 ? '0' + hour : hour
let minute = date.getMinutes()//获取分
minute = minute < 10 ? '0' + minute : minute
let second = date.getSeconds()//获取秒
second = second < 10 ? '0' + second : second
return `${year}年${month}月${day}日${hour}时${minute}分 ${second}秒`
}
let div = document.querySelector('div')
div.innerHTML = getTime()
setInterval(function () {
div.innerHTML = getTime()
}, 1000)
</script>
</body>
</html>