【问题标题】:How to optimize Javascript to make it shorter如何优化 Javascript 以使其更短
【发布时间】:2015-12-19 00:09:09
【问题描述】:

我是编码新手,我希望优化这段 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>

【问题讨论】:

    标签: javascript html css optimization


    【解决方案1】:

    就像你说的使用变量。只需使用小时数并在小于 10 时填充它。

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

    【讨论】:

    • 你能告诉我为什么我应该使用“if (currentTime
    • @Wally - 那部分是总是有两位数的值......(在左边添加零)
    【解决方案2】:
    var currentTime = new Date().getHours();
    var cls = "sky-gradient-";
    
    if (currentTime < 10) {
       cls = cls + "0" + currentTime;
    } else {
       cls += currentTime ;
    }
    document.body.className = cls;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-05-29
      • 1970-01-01
      • 2020-01-13
      • 2012-10-22
      • 2011-05-07
      • 1970-01-01
      • 2016-05-07
      • 1970-01-01
      相关资源
      最近更新 更多