javascript - 如何使用js或jquery获取超时时间

标签 javascript jquery

我想根据一定的时间添加一个类(class),如果时间到了,那么该类(class)会自动被删除。我反复尝试,但无法弄清楚,因为我对 JavaScript/jQuery 很陌生。我尝试用谷歌搜索解决方案,但找不到任何东西,这让我找到了 StackOverflow。请引用我下面的代码。

$(document).ready(function() {
  var hr = new Date().getHours();
  // I want execute this at 20:00 till 04:00
  if (hr < 20) {
    $('#tahajud').addClass('opened-for-codepen');
  }
  // I want execute this at 04:00 till 06:00
  if (hr < 4) {
    $('#fajr').addClass('opened-for-codepen');
  }
  // I want execute this at 08:00 till 10:00
  if (hr < 8) {
    $('#dhuha').addClass('opened-for-codepen');
  }
});

最佳答案

您可以使用一系列 ifelse if 来检查您的 hr 是否落在您想要的时间之间。 CSS 很重要,因为它默认将所有 div 隐藏,并且该类显示它添加到的任何 div。

$(document).ready(function() {
  var hr = new Date().getHours();

  // fluff for the example
  $('body').prepend('Setting class for hour ' + hr + '...');


  // adds the class by calling the function after 1.5 seconds
  setTimeout(setCodepenClass.bind(null, hr), 1500);
});

function setCodepenClass(hr) {

  // Adds the class if time is between 04:00 (inclusive) and 06:00 (exclusive)
  if (hr >= 4 && hr < 6) {
    $('#fajr').addClass('opened-for-codepen');
  }
  // Adds the class if time is between 08:00 (inclusive) and 10:00 (exclusive)
  else if (hr >= 8 && hr < 10) {
    $('#dhuha').addClass('opened-for-codepen');
  }
  // Adds the class if time is between 20:00 (inclusive) and 04:00 (exclusive)
  else if (hr >= 20 || hr < 4) {
    $('#tahajud').addClass('opened-for-codepen');
  }
}
div {
  display: none;
}

.opened-for-codepen {
  background: #333;
  border: 2px solid #222;
  color: white;
  display: block;
  font-weight: bold;
  margin: 2em;
  min-width: 200px;
  min-height: 75px;
  padding: 2em;
  text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="tahajud">tahajud</div>
<div id="fajr">fajr</div>
<div id="dhuha">dhuha</div>

关于javascript - 如何使用js或jquery获取超时时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43220677/

相关文章:

javascript - 使用 jquery/js 获取下一个元素

javascript - 严格所有插件特定规则

javascript - 如何在 WordPress 站点内使用 PHP 来查找散列的 bundle.js 文件并将适当的文件名插入到脚本标记中?

javascript - 这两种从 Javascript 模块导出的方式有什么区别?

javascript - Highcharts - 重叠的散点图标签不可读

javascript - 函数在我的案例中无法执行

php - 如何从 Bootstrap 模式在ajax中发布数据?

jquery - 设置 JQuery event.preventDefault() 时绕过 window.open 上的弹出窗口阻止程序

javascript - jQuery 全日历 : Change the color of every saturday except last saturday in the month

Javascript 闭包对象属性访问器