Change Background with CSS on particular date?

后端 未结 4 780
灰色年华
灰色年华 2021-01-14 01:40

Does anyone know how to change the background of a website automatically using CSS on specific dates? Like valentines, easter, xmas etc.

4条回答
  •  时光说笑
    2021-01-14 02:41

    You'll have to use either a server-side language like PHP or JavaScript for this. With PHP, for example, you can access the server date/time with date() and do something like:

    if(date('m/d') == '2/14'))
        'get your girl a present, dude!';
    

    The upside of using server-side code is that it's faster for the user. The disadvantage is that it's your server's date and time, not the user's. So you could do the same thing with Javascript, like so:

    var curtime = new Date(),
        curday = curtime.getDate(),
        curmonth = curtime.getMonth()+1;
    
    if(curmonth == 2 && curday == 14)
       alert('better be quick');
    

    Either way will work.

    Added for clarity: The above will allow you to check the day. You can then use that to add a CSS class to your HTML element, for example, which you've prepared for that day. Say you do it with Javascript, you'd write

    $('#wrap').addClass('valentines');
    

    instead of the alert() above. This will add the class valentines to the

    - just as an example. You can then do whatever you like with that CSS class.

    Edit: I used jQuery in the last snippet. You can do it with Javascript alone too - Loktar already added that in his answer.

提交回复
热议问题