开发者

Change Background with CSS on particular date?

Does anyone know how to change the background of a website automatically using CSS on specific dates? Like valentine开发者_运维问答s, easter, xmas etc.


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 <div id="wrap"> - 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.


You cannot do this with css. You would need to use JavaScript to do it.

For example to change background color to red on valentines day:

var date = new Date();
if(date.getDate() == 14 && date.getMonth() == 1) {
    document.body.style.background = "red";
}


You wont be able to do it using only css but you could do it combining javascript and css like so,

var checkDate=new Date(),
today = new Date();
checkDate.setFullYear(2011,1,14);

if (today.getTime() === checkDate.getTime()){
    document.getElementById("background").className += 'valentinesBackgroundStyle';
}

http://jsfiddle.net/sH429/


var date = new Date(),
    day = date.getDate(),
    month = date.getMonth()+1;

if (10 == month && 31 == day) {
    document.body.style.backgroundColor = "#FF9100";
}

Notice I added one (1) because the getMonth() method returns the month from 0 to 11 for the specified date, according to local time.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜