未捕获的类型错误:无法设置未定义的属性“transform”
2019-01-08
11188
我正在做这个时钟项目,我需要将变换属性应用于时针进行旋转,但我遇到了这个错误。我检查了我的 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个回答
您可以做这样的事情。
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>
Ruslan Kolibabchuk
2019-01-08
将
time()
函数中的变量名
hour
更改为简写版本
hr
,并在
hourdegree
变量赋值中将
(min/12)
更改为
(hr/12)
。
function time(){
/* other code */
const hr= date.getHours();
const hourDegree = ((hr/12) * 360) + 90;
hour.style.transform = `rotate(${hourDegree}deg)`;
}
AndrewL64
2019-01-08