我有一个 href 按钮,我需要根据一天中的时间隐藏它或像这样更改背景颜色:
<a class="button not-active " href="updateScheduleRequest.php?slotid=4&timeremain=120&current_date=2015-08-28&empnum=107">Assign Slot 4</a>
我的 CSS 配置为:
.button {
}
/* daytime */
.day
{
background-color:#e0d0b7 !important;
}
/* Sunset */
.sunset
{
background-color:#887f70 !important;
}
/* Nightime */
.night
{
display:hidden !important;
}
然后我的 jQuery 被分解来处理一天中的时间,但它根本没有对按钮进行任何更改?我错过了什么?
// Change background depending on user's time
function applyclass()
{
var d = new Date();
var n = d.getHours();
if (n > 19)
// If time is 7PM or later apply night theme to 'body'
$('button').addClass('night');
else if (n > 16 && n < 19)
// If time is between 4PM – 7PM sunset theme to 'body'
$('button').addClass('sunset');
else
// Else use 'day' theme
$('button').addClass('day');
}
window.onload = applyclass;
最佳答案
您可以考虑使用 switch 语句代替 if/else if/else。它稍微整理了代码:
function applyclass() {
var d = new Date();
var n = d.getHours();
switch(true) {
case (n > 19) :
buttonClass = 'night';
break;
case (n > 16 && n < 19) :
buttonClass = 'sunset';
break;
default:
buttonClass = 'day';
}
$('.button').addClass(buttonClass);
}
此外,考虑使用默认样式(如“day”类中的样式)设置 .button 元素的样式,然后仅在必要时应用附加类来覆盖这些样式。这比在每种情况下都依赖修饰符类要简单。
希望这对您有所帮助!
关于javascript - jQuery/CSS 脚本根据一天中的时间更改按钮颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33398214/