我正在尝试根据时间更改此元素:文本
我找到了这个片段,但是我应该更改/添加什么才能影响 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/