Change Background with CSS on particular date?

后端 未结 4 779
灰色年华
灰色年华 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:22

    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";
    }
    
    0 讨论(0)
  • 2021-01-14 02:33

    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/

    0 讨论(0)
  • 2021-01-14 02:37
    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 讨论(0)
  • 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 <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.

    0 讨论(0)
提交回复
热议问题