gpt4 book ai didi

javascript - 根据季节( Spring 、夏季、秋季、冬季)更改 CSS 中
的背景图像

转载 作者:太空狗 更新时间:2023-10-29 12:30:12 28 4
gpt4 key购买 nike

我有一个特定日期的 javascript 倒计时,我想根据季节( Spring 、夏季、秋季、冬季)更改部分的背景图像

4 季时间表: Spring (三月至五月)夏季(六月至八月)秋季(九月至十一月)冬季(十二月至二月)

我会在我的脚本代码中声明一个具体日期,它的倒计时将在 2020 年 10 月 15 日结束,我还想不出任何逻辑,所以我寻求帮助:) 谢谢!

这是我的javascript代码:

function dateCountdown() {
const second = 1000,
minute = second * 60,
hour = minute * 60,
day = hour * 24;

//set the timer here
let countDown = new Date('Oct 15, 2020 00:00:00').getTime(),
x = setInterval(function () {

let now = new Date().getTime(),
distance = countDown - now;

document.getElementById('days').innerText = Math.floor(distance / (day)),
document.getElementById('hours').innerText = Math.floor((distance % (day)) / (hour)),
document.getElementById('minutes').innerText = Math.floor((distance % (hour)) / (minute)),
document.getElementById('seconds').innerText = Math.floor((distance % (minute)) / second);

//do something later when date is reached
//if (distance < 0) {
// clearInterval(x);
// 'IT'S TIME!;
//}

}, second)
}

这是 HTML 代码:

      <section class="section-countdown">
<h2>THIS CONGRESS BEGINS IN</h2>
<ul class="countdown">
<li>
<span id="days"></span>
<p class="days_ref">DAYS</p>
</li>
<li class="seperator">:</li>
<li>
<span id="hours"></span>
<p class="hours_ref">HOURS</p>
</li>
<li class="seperator">:</li>
<li>
<span id="minutes"></span>
<p class="minutes_ref">MINUTES</p>
</li>
<li class="seperator">:</li>
<li>
<span id="seconds"></span>
<p class="seconds_ref">SECONDS</p>
</li>
</ul>
</section>

最佳答案

您可以尝试以下方法来获取季节:

function getSeason() {
var currentMonth = new Date().getMonth() + 1;
if (currentMonth === 12 || currentMonth === 1 || currentMonth === 2)
return "winter";
else if (currentMonth >= 3 && currentMonth <= 5)
return "spring";
else if (currentMonth >= 6 && currentMonth <= 8)
return "summer";
else if (currentMonth >= 9 && currentMonth <= 11)
return "fall";
return ""
}

然后创建一个如下函数来为你想要的元素设置背景图片:

function setBackground() {
var image = "";
switch (getSeason()) {
case "winter":
image = imageurlhere;
break;
case "spring":
image = imageurlhere;
break;
case "summer":
image = imageurlhere;
break;
case "fall":
image = imageurlhere;
break;
default:
break;
}
document.getElementByClassName("section-countdown").style.backgroundImage = 'url(image)';
}

编辑:我的错误 getMonth() 是从零开始的,我已经在上面进行了更改。

关于javascript - 根据季节( Spring 、夏季、秋季、冬季)更改 CSS 中 <section> 的背景图像,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52308350/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com