未捕获的TypeError:无法设置未定义的属性“ transform”

时间:2019-01-08 20:27:20

标签: javascript html

我正在做这个时钟项目,我需要将transform属性应用于时针进行旋转,但是出现此错误。我检查了HTML,所有选择器都是正确的。

const hour = document.querySelector('.hour');
const minute = document.querySelector('.minute');
const second = document.querySelector('.second');

function time(){
  const date = new Date();
  const sec = date.getSeconds();
  const secDegree = ((sec/60) * 360) + 90;
  second.style.transform = `rotate(${secDegree}deg)`;

  const min = date.getMinutes();
  const minDegree = ((min/60) * 360) + 90;
  minute.style.transform = `rotate(${minDegree}deg)`;

  const hour = date.getHours();
  const hourDegree = ((min/12) * 360) + 90;
  hour.style.transform = `rotate(${hourDegree}deg)`;
}

setInterval(time, 1000);

// html

    <div class="clockFace">
        <div class="hand minute"></div>
        <div class="hand hour"></div>
        <div class="hand second"></div>
    </div>

2 个答案:

答案 0 :(得分:0)

hour函数内的变量名称time()更改为简写版本hr,并在hourdegree变量分配中,将(min/12)更改为{{1 }}。

(hr/12)

答案 1 :(得分:0)

您可以执行以下操作。

const hour = document.querySelector('.hour');
const minute = document.querySelector('.minute');
const second = document.querySelector('.second');

function time(){
  const date = new Date();
  const sec = date.getSeconds();
  const secDegree = ((sec/60) * 360) + 90;
  second.style.transform = `rotate(${secDegree}deg)`;
  second.innerText = secDegree;

  const min = date.getMinutes();
  const minDegree = ((min/60) * 360) + 90;
  minute.style.transform = `rotate(${minDegree}deg)`;
  minute.innerText = minDegree ;

  const hr = date.getHours();
  const hourDegree = ((min/12) * 360) + 90;
  hour.style.transform = `rotate(${hourDegree}deg)`;
  hour.innerText = hr;
}

setInterval(time, 1000);
    .hour {
      height: 6px;
      background: red;
    }
    .minute {
      height: 4px; 
      background: green;
    }
    .second {
      height: 2px;
      background: blue;
    }
<html>
<head></head>
<body>
<div style="width: 200px; height: 200px; margin: 50px;" class="clockFace">
        <div class="hand minute"></div>
        <div class="hand hour"></div>
        <div class="hand second"></div>
    </div>
    
</body>
</html>