如何使用JavaScript根据季节更改body
的背景?
我有以下代码:
// 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>
答案 0 :(得分:2)
只需将一个类添加到正文:document.body.classList.add(getSeason())