简体   繁体   中英

How to change background of body based on current date with javascript?

How do I change the background of my body based on season with javascript?

I have following code:

 // Return the southern hemisphere season for a date // If no date provided, uses current system date function getSeason(d) { d = d || new Date(); var mon = d.getMonth() + 1; // Adjust to be indexed from 1 var day = d.getDate(); var seasons = ['summer','autumn','winter','spring']; // Do silly seasons here if (mon == 12) { if (day >= 13 && day <= 27) { return 'spring'; } if (day >= 28 && day <= 31) { return 'spring'; } } // If wasn't a silly season, do others mon = Math.floor((mon % 12) / 3); return seasons[mon]; } 
 .spring { background: green; } .summer { background: red; } .autumn { background: brown; } .winter { background: aquamarine; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <script> $(document).ready(function(){ document.body.classList.add(getSeason()) }); </script> <body class="getSeason"> Hello There </body> 

只需将一个类添加到主体: document.body.classList.add(getSeason())

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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