为什么下面的这段代码没有显示预期的结果

问题描述

所以我当时正在使用HTML / CSS / JS制作数字时钟,但由于某种原因,它无法按我期望的方式工作。任何建议吗?提前致谢! 它在代码段上工作正常,但是当我尝试在浏览器中打开它时,我只会看到黑色背景...。

function startTime(){
  var date = new Date()
  var h = date.getHours() // 0 - 23
  var m = date.getMinutes() // 0 - 59
  var s = date.getSeconds() // 0 - 59
  var session = "AM"

  if (h == 0){
    h = 12
  }

  if (h > 12){
    h = h - 12 
    session = "PM"
  }

  h = (h < 10)? "0" + h : h
  m = (m < 10)? "0" + m : m
  s = (s < 10)? "0" + s : s
   
  var time = h + ":" + m + ":" + s + " " + session
  document.getElementById("digclock").innerHTML = time
  document.getElementById("digclock").textContent = time

  setTimeout(startTime,1000) //1000ms = 1sec
}

startTime()
    body {
    background: black;
}

.clock {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translateX(-50%) translateY(-50%);
    color: #17D4FE;
    font-size: 60px;
    font-family: Orbitron;
    letter-spacing: 7px;
<html lang="en">
<head>
    <Meta charset="UTF-8">
    <Meta name="viewport" content="width=device-width,initial-scale=1.0">
    <title>Document</title>
    <link rel="stylesheet" href="main.css">
    <script src="main.js"></script>
    
</head>
<body>
    <div class="clock" id="digclock" onload="startTime()"></div>
</body>
</html>

解决方法

在下面的代码段中,我添加了所需任务的CSS。由于body { background-color: black; },背景颜色为黑色。 要在时钟中给时钟加色,请使用{ color: green; }。然后,如代码段所示,我用包装纸将时钟垂直和水平居中。

function startTime(){
  var date = new Date();
  var h = date.getHours(); // 0 - 23
  var m = date.getMinutes(); // 0 - 59
  var s = date.getSeconds(); // 0 - 59
  var session = "AM";

  if (h == 0){
    h = 12;
  }

  if (h > 12){
    h = h - 12; 
    session = "PM";
  }

  h = (h < 10)? "0" + h : h;
  m = (m < 10)? "0" + m : m;
  s = (s < 10)? "0" + s : s;
   
  var time = h + ":" + m + ":" + s + " " + session;
  document.getElementById("digclock").innerHTML = time;
  document.getElementById("digclock").textContent = time;

  setTimeout(startTime,1000); //1000ms = 1sec
}

startTime();
body {
  background-color: black;
}

.wrapper {
  display: table;
  text-align: center;
  color: green;
  height: calc(100vh - 1em);
  width: 100%;
}

.clock {
  display: table-cell;
  vertical-align: middle;
}
<div class="wrapper"> 
  <div class="clock" id="digclock" onload="startTime()">
  </div>
</div>