How to display only at certain times of the day in html?

时间:2019-04-08 13:36:12

标签: html scheduler

I am trying to get an image to appear and disappear at certain times of the day using HTML.

Any code snippets would be appreciated.

3 个答案:

答案 0 :(得分:0)

这是一种已经过测试并且可以正常工作的解决方案。这可用于显示所需的任何HTML。在这种情况下,我已经用<img>标签加载了代码。

<!DOCTYPE html>
<html>
<body>

<!-- Set an Element with a specific ID -->
<div id="elementID"></div>
<div id="SecondImageHolder"></div>


<script>
//Useful methods:
//Date.getHours()
//Date.getMinutes()
//Date.getSeconds()
var date = new Date()
if(date.getHours() > 7 && date.getHours() < 12) //If time is between 8:00 and 12:00
{
    document.getElementById("elementID").innerHTML = "<img src=\"Your_Image_PATH\" alt=\"Alternative Text Here\" height=\"50\" width=\"50\">";
    document.getElementById("SecondImageHolder").innerHTML = "<img src=\"Your_Second_Image_PATH\" alt=\"Alternative Text Here\" height=\"50\" width=\"50\">";
    //Add as many as you need . . .
}

</script>

</body>
</html> 

如果您希望两个图像在不同的时间打开/关闭,请在每个图像添加项中添加如下所示的条件

<!DOCTYPE html>
<html>
<body>

<!-- Set an Element with a specific ID -->
<div id="elementID"></div>
<div id="SecondImageHolder"></div>


<script>
var date = new Date()
if(date.getHours() > 7 && date.getHours() < 12) //If time is between 8:00 and 12:00
{
    document.getElementById("elementID").innerHTML = "<img src=\"Your_Image_PATH\" alt=\"Alternative Text Here\" height=\"50\" width=\"50\">";
    //Add as many as you need . . .
}

if(date.getHours() > 9 && date.getHours() < 12) //If time is between 10:00 and 12:00    {
    document.getElementById("SecondImageHolder").innerHTML = "<img src=\"Your_Second_Image_PATH\" alt=\"Alternative Text Here\" height=\"50\" width=\"50\">";
    //Add as many as you need . . .
}

</script>

</body>
</html> 

可以在here中找到JavaScript的Date方法的扩展列表。

编辑

根据评论之一,请注意,可以通过添加一些额外的行(如上所示)将其扩展为包含多张图像。

答案 1 :(得分:0)

根据您的简短描述,我会这样做。

git gc

答案 2 :(得分:0)

如果按时间表示,您是指UTC时间,则需要JavaScript和一个if循环。
这里会根据时间而产生不同的问候。

<html>
<body>

<p>Click the button to get a time-based greeting:</p>

 <button onclick="myFunction()">Try it</button>

<p id="demo"></p>

<script>
function myFunction() {
  var greeting;
  var time = new Date().getHours();
  if (time < 10) {
    greeting = "Good morning";
  } else if (time < 20) {
    greeting = "Good day";
  } else {
    greeting = "Good evening";
  }
  document.getElementById("demo").innerHTML = greeting;
  }
  </script>

  </body>
  </html>

https://www.w3schools.com/js/tryit.asp?filename=tryjs_elseif