javascript - 我可以根据一天中的时间对 HTML 中的内容可见性进行计时吗?

标签 javascript php html

我有一个本地站点,我想在一天中的特定时间显示特定部分 (divs)。这可能吗?如果是这样,我该如何实现?谢谢。

我有这个简单的示例页面:

<!DOCTYPE html>
<html lang="en">
<head>
  <title>timed content</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
</head>
<body> 

<div class="container">
   <h2>timed content</h2>
   <div id="eight" class="well">only show 8AM</div>
  
   <div id="eleven" class="well">only show at 11AM</div>
  
   <div id="three" class="well">only show at 3PM</div>
</div>
</body>
</html>

最佳答案

您可以使用 JS 通过使用 Date 对象来实现这一点,并在每个元素上提供一些关于您希望在什么时间显示它的数据。

let now = new Date(); // Get the current time
let elem = document.querySelector(`div[data-hour="${now.getHours()}"]`); // Select the element that's supposed to be shown for the current time

if (elem) { // If its exists, show it
  elem.style.display = 'block';
}
div[data-hour] {
  /* By default hide all elements that are "timed" */
  display: none;
}
<div class="container">
  <h2>timed content</h2>
  <div data-hour="0">0:00</div>
  <div data-hour="1">1:00</div>
  <div data-hour="2">2:00</div>
  <div data-hour="3">3:00</div>
  <div data-hour="4">4:00</div>
  <div data-hour="5">5:00</div>
  <div data-hour="6">6:00</div>
  <div data-hour="7">7:00</div>
  <div data-hour="8">8:00</div>
  <div data-hour="9">9:00</div>
  <div data-hour="10">10:00</div>
  <div data-hour="11">11:00</div>
  <div data-hour="12">12:00</div>
  <div data-hour="13">13:00</div>
  <div data-hour="14">14:00</div>
  <div data-hour="15">15:00</div>
  <div data-hour="16">16:00</div>
  <div data-hour="17">17:00</div>
  <div data-hour="18">18:00</div>
  <div data-hour="19">19:00</div>
  <div data-hour="20">20:00</div>
  <div data-hour="21">21:00</div>
  <div data-hour="22">22:00</div>
  <div data-hour="23">23:00</div>
</div>

如果您不仅要检查当前时间,还需要为每个元素提供更多数据并进行检查。如果您希望在特定时间显示多个元素,请使用 document.querySelectorAll 并迭代结果。

关于javascript - 我可以根据一天中的时间对 HTML 中的内容可见性进行计时吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60351500/

相关文章:

javascript - 添加位置 : fixed; ruins the header

javascript - AngularJS push() 错误

php - 通过 HTML 表单插入数据的 SQL Near 错误

PHP bind_param 崩溃并出现 500 Internal Server Error

javascript - 如何从两个单独的 HTML id 中复制一个值?

javascript - <a> 元素内的链接不起作用

javascript - 以像素为单位的 OpenLayers 特征

php - 如何在 Symfony2 中使用 Swiftmailer 将 PDF 附加到电子邮件

html - 标签很长时标签重叠文本框 - css

javascript - 添加 HTML 文本框来修改 JS 数组项?要学习的最佳实践和资源?欢迎任何建议