我是编码的新手,我正在寻求优化此JavaScript代码? 你有什么建议?我应该使用变量倒小时数吗? 如果让它更短,我怎么能尝试不重复相同的其他呢?
var currentTime = new Date().getHours();
if (0 == currentTime) {
document.body.className = "sky-gradient-00";
}
else if (1 == currentTime) {
document.body.className = "sky-gradient-01";
}
...
else if (22 == currentTime) {
document.body.className = "sky-gradient-22";
}
else if (23 == currentTime) {
document.body.className = "sky-gradient-23";
}

html,
body {
height: 100%;
width: 100%;
}
.sky-gradient-00,
.sky-gradient-24 {
background: #00000c;
}
.sky-gradient-01 {
background: linear-gradient(to bottom, #020111 85%, #191621 100%);
}
.sky-gradient-22 {
background: linear-gradient(to bottom, #090401 50%, #4B1D06 100%);
}
.sky-gradient-23 {
background: linear-gradient(to bottom, #00000c 80%, #150800 100%);
}

<html>
<body class="">
</body>
</html>
&#13;
答案 0 :(得分:3)
就像你说的那样使用一个变量。只需使用小时数并在小于10时填充它。
if(currentTime < 10) currentTime = "0" + currentTime;
document.body.className = "sky-gradient-" + currentTime;
答案 1 :(得分:0)
var currentTime = new Date().getHours();
var cls = "sky-gradient-";
if (currentTime < 10) {
cls = cls + "0" + currentTime;
} else {
cls += currentTime ;
}
document.body.className = cls;