javascript - 如何优化 Javascript 使其更短

标签 javascript html css optimization

我是编码新手,我想优化这段 JavaScript 代码? 你有什么建议?我应该使用变量来倒小时数吗? 我怎么能尝试不重复相同的 else if 并使其更短?

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>

最佳答案

就像你说的那样使用变量。小时数不足10时补上即可。

if(currentTime < 10) currentTime = "0" + currentTime;
document.body.className = "sky-gradient-" + currentTime;

关于javascript - 如何优化 Javascript 使其更短,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30714199/

相关文章:

javascript - 如何使用 jquery 以简短形式显示和隐藏一长串 div

javascript - 未捕获的类型错误 : Object #<NodeList> has no method 'addEventListener'

javascript - 旋转放置在圆圈上的图像列表 <li> 点击任何 child 到给定位置

jquery - 使用jQuery从右向左滑动div

javascript - 3 网格布局 : fixed sidebars and fluid content

javascript - React Native 和 Apollo : Can't find variable: document

javascript - request.status 和 request.statusCode 之间的区别

html - 两个图像链接之间的下划线

javascript - 文本在我的 Canvas 上被垂直拉伸(stretch),使其不可读

javascript - 如何统一更改字体大小?