javascript - jQuery/CSS 脚本根据一天中的时间更改按钮颜色

标签 javascript jquery css

我有一个 href 按钮,我需要根据一天中的时间隐藏它或像这样更改背景颜色:

<a class="button not-active " href="updateScheduleRequest.php?slotid=4&amp;timeremain=120&amp;current_date=2015-08-28&amp;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/

相关文章:

html css z-index 不工作,我做错了什么?

javascript - 如何在JS中修复数字的负号

javascript - experimentalObjectRestSpread 在 ESLint 中不起作用

javascript - 将 p 标签值限制为一行并在最后一个完整单词后中断

javascript - 如何插入允许用户在开始时选择秒数的功能?

html - CSS - 图像容器 div 与图像大小不同

html - 在不改变移动顺序的情况下对齐右引导导航栏教程

javascript - 如何托管 html 文件,如 css 和 javascript 文件

javascript - jQuery 在 div 和切换类之外找到下一个类

javascript - 包含来自其他网站的 html 文件吗?