文章目录
页面显示时间练习
404 Not Found
2024-11-07 15:35
累计阅读3
评论0

页面显示时间练习

需求:将当前时间以:YYYY-MM-DD HH:mm 形式显示在页面 2008-08-08 08:08

分析

  1. 调用日期对象方法进行转换
  2. 记得数字要补0
  3. 字符串拼接后,通过 innerText 给 标签

代码实现

<!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: 500px;
      height: 50px;
      border: 3px solid pink;
      border-radius: 10px;
      top: 0;
      bottom: 0;
      left: 0;
      right: 0;
      margin: auto;
      text-align: center;
      line-height: 50px;
      position: absolute;
      font-size: 30px;
      color: skyblue;
    }
  </style>
</head>

<body>
  <div></div>
  <script>
    const div = document.querySelector('div')
    function getMyDate() {
      const date = new Date()
      let h = date.getHours()
      let m = date.getMinutes()
      let s = date.getSeconds()
      h = h < 10 ? '0' + h : h
      m = m < 10 ? '0' + m : m
      s = s < 10 ? '0' + s : s
      return `今天是: ${date.getFullYear()}年${date.getMonth() + 1}月${date.getDate()}日 ${h}:${m}:${s}`
    }
    div.innerHTML = getMyDate()
    setInterval(function () {
      div.innerHTML = getMyDate()
    }, 1000)
  </script>
</body>

</html>

效果示例

屏幕截图 2023-11-20 163943.png

评论
404NotFound
Powered by Halo Themed by Shine
haoanlan
haoanlan
haoanlan