jQuery/CSS脚本根据一天中的时间更改按钮颜色 [英] jQuery/CSS script change button color based on time of day

查看:73
本文介绍了jQuery/CSS脚本根据一天中的时间更改按钮颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a a href button that I need to hide depending on the time of day or changed the background color like this:

<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被打破以处理这样的一天中的时间,但是它根本没有对按钮进行任何更改?我想念什么?

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

推荐答案

您可以考虑使用switch语句代替if/else if/else.它整理了一下代码:

You may consider using a switch statement instead of 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);
}

此外,请考虑使用默认样式(如"day"类中的样式)对.button元素进行样式设置,然后仅在必要时应用其他类以覆盖这些样式.这比每种情况下都依赖修饰符类要简单.

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. It's simpler than relying on a modifier class for each and every case.

希望这会有所帮助!

这篇关于jQuery/CSS脚本根据一天中的时间更改按钮颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆