根据一天中的时间设置网站的主题(无需外部库)

2025-06-07

根据一天中的时间设置网站的主题(无需外部库)

在这篇博文中,我将向您展示如何使用 JavaScript 和 CSS 根据一天中的时间设置网站主题。如果您想创建一个根据一天中的时间自动切换明暗主题的网站,这项功能将非常有用。读完这篇文章后,您将拥有一个能够根据一天中的时间自动更改外观的网站,从而打造更具活力、更引人入胜的用户体验。

在继续之前,请记住,无论是否编写代码,您都可以在DoTenX免费实现您的网站或落地页。请务必查看,甚至可以提名您的作品在那里展示。


首先,我们将创建两个 CSS 样式表,一个用于浅色主题,一个用于深色主题。这两个样式表将定义网站上使用的颜色和其他样式。

/* light.css */

body {
  background-color: white;
  color: black;
}

/* dark.css */

body {
  background-color: black;
  color: white;
}
Enter fullscreen mode Exit fullscreen mode

接下来,我们将使用 JavaScript 检测当前时间并将适当的样式表应用于 HTML 页面的元素。

<!DOCTYPE html>
<html>
<head>
  <title>Time-Based Theme Example</title>

  <script>
    // Get the current time
    var date = new Date();
    var hour = date.getHours();

    // Apply the light or dark stylesheet based on the time of day
    if (hour >= 6 && hour < 18) {
      // If the time is between 6am and 6pm, use the light theme
      var link = document.createElement("link");
      link.setAttribute("rel", "stylesheet");
      link.setAttribute("type", "text/css");
      link.setAttribute("href", "light.css");
      document.head.appendChild(link);
    } else {
      // Otherwise, use the dark theme
      var link = document.createElement("link");
      link.setAttribute("rel", "stylesheet");
      link.setAttribute("type", "text/css");
      link.setAttribute("href", "dark.css");
      document.head.appendChild(link);
    }
  </script>
</head>
<body>
  <h1>Time-Based Theme Example</h1>
  <p>This page demonstrates how to use JavaScript, HTML, and CSS to set the theme of a website based on the time of day.</p>
</body>
</html>
Enter fullscreen mode Exit fullscreen mode

在这个例子中,我们使用 JavaScript 中的 Date 对象来获取当前时间,然后使用 if 语句来判断时间是否在上午 6 点到下午 6 点之间。如果是,则应用浅色主题样式表;如果不是,则应用深色主题样式表。

您可以根据需要调整时间和样式,还可以使用其他样式表和 JavaScript 代码为您的网站创建更复杂、更精致的主题。

文章来源:https://dev.to/mohsenkamrani/set-the-theme-of-a-website-based-on-the-time-of-the-day-no-external-library-5ank
PREV
了解 .NET 8 中的后台服务:IHostedService 和 BackgroundService
NEXT
REST API 设计的 8 个最佳实践