我想根据一定的时间添加一个类(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');
}
});
最佳答案
您可以使用一系列 if
和 else 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/