简体   繁体   English

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

[英]jQuery/CSS script change button color based on time of day

I have aa href button that I need to hide depending on the time of day or changed the background color like this: 我有一个aa 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>

My CSS is configured as: 我的CSS配置为:

.button {
}
/* daytime  */
.day
{
    background-color:#e0d0b7 !important;
}
/* Sunset  */
.sunset
{
    background-color:#887f70 !important;
}
/* Nightime  */
.night
{
    display:hidden !important;
}

And then my jQuery is broken out to handle the time of day like this but it is not making any changes to the button at all? 然后我的jQuery被打破以处理这样的一天中的时间,但是它根本没有对按钮进行任何更改? What am I missing? 我想念什么?

// 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;

You may consider using a switch statement instead of if/else if/else. 您可以考虑使用switch语句代替if / else if / else。 It tidies up the code a bit: 它整理了一下代码:

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);
}

Also, consider styling the .button element with default styles (like those in the 'day' class) and then only apply an additional class when necessary to override those styles. 另外,请考虑使用默认样式(如“ day”类中的样式)来样式化.button元素,然后仅在必要时应用其他类以覆盖这些样式。 It's simpler than relying on a modifier class for each and every case. 这比每种情况下都依赖修饰符类要简单。

Hope this helps! 希望这可以帮助!

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM