gpt4 book ai didi

javascript - 根据时间改变元素

转载 作者:行者123 更新时间:2023-12-03 05:35:12 24 4
gpt4 key购买 nike

我正在尝试根据时间更改此元素:文本

我找到了这个片段,但是我应该更改/添加什么才能影响 h1?

var myDate = new Date();  

/* hour is before noon */
if ( myDate.getHours() < 12 ) {
document.write("Good Morning!");
}

/* Hour is from noon to 5pm (actually to 5:59 pm) */
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 ) {
document.write("Good Afternoon!");
}

/* the hour is after 5pm, so it is between 6pm and midnight */
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 ) {
document.write("Good Evening!");
}

/* the hour is not between 0 and 24, so something is wrong */
else {
document.write("I'm not sure what time it is!");
}

提前致谢!

最佳答案

您的页面上需要有一个h1标签,您可以赋予'id'属性并根据当前时间更改内容:下面的代码可能会帮助您

var myDate = new Date();   /* hour is before noon */ if ( 
myDate.getHours() < 12 ) {
document.getElementById('greeting').innerHTML ="Good Morning!"; }
else if ( myDate.getHours() >= 12 && myDate.getHours() <= 17 )
{ document.getElementById('greeting').innerHTML ="Good Afternoon!"; }
else if ( myDate.getHours() > 17 && myDate.getHours() <= 24 )
{ document.getElementById('greeting').innerHTML= "Good Evening!"; }
else
{ document.getElementById('greeting').innerHTML="I'm not sure what time it is!"; }
<h1 id="greeting"></h1>

关于javascript - 根据时间改变元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40759946/

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