首页 > 解决方案 > 根据最终用户的时间调用样式表的 js 代码优化

问题描述

以下代码有效。这很简单,但我确信在不使用 jquery 的情况下会有更好和/或更优化的方式来编写它,但我不知道有任何其他方式可以做到这一点并让它像现在一样工作。

<script>
function getStylesheet() {
    var currentTime = new Date().getHours();
    if (5 <= currentTime&&currentTime < 11) {
        document.write("<link rel='stylesheet' href='{T_THEME_PATH}/morning.css'>");
    }
    if (11 <= currentTime&&currentTime < 16) {
     document.write("<link rel='stylesheet' href='{T_THEME_PATH}/day.css'>");
    }
    if (16 <= currentTime&&currentTime < 22) {
     document.write("<link rel='stylesheet' href='{T_THEME_PATH}/evening.css'>");
    }
    if (22 <= currentTime&&currentTime <= 24 || 0 <= currentTime&&currentTime < 5) {
     document.write("<link rel='stylesheet' href='{T_THEME_PATH}/night.css'>");
    }
}

getStylesheet();

编辑:我只需要知道是否有更好的方法来编写我发布的 js。更好的是我有什么缺陷或不正确的编码

标签: javascript

解决方案


尽管主要问题是在插入元素时使用document.write它通常被认为是不好的做法,但您的方法对于您正在做的事情大多是好的。如果你想稍微清理一下,你可以做这样的事情,它专注于断点而不是值的范围:

function getStylesheet() {
  const currentTime = new Date().getHours();
  const breaks = [5, 11, 16, 22, 24];
  const extensions = ['night', 'morning', 'afternoon', 'evening', 'night'];
  const match = breaks.findIndex(num => currentTime < num);

  const head = document.getElementsByTagName('head')[0];
  const sheetLink = document.createElement('link');
  sheetLink.rel = 'stylesheet';
  sheetLink.href = `T_THEME_PATH/${extensions[match]}.css`;

  head.appendChild(sheetLink);
}

getStylesheet();

这种方法假定时间格式始终为 0-24,并且要求两个数组完全相关,因此它不是那么灵活,但您可能喜欢使用它。它还使用模板文字来构造href一次,而不是多次写出。

最后一点 - 您的代码中没有 jQuery,它都是香草 javascript。


推荐阅读