如何在白天和黑夜自动切换页面的颜色?

要实现网页颜色根据白天和黑夜自动切换,你可以使用 JavaScript 检测用户系统的时间或地理位置,然后动态地更改 CSS 样式。以下提供两种方法及代码示例:

方法一:根据系统时间切换

这种方法较为简单,根据用户电脑的时间判断是白天还是黑夜。 可以设定一个阈值,例如早上 6 点到晚上 6 点是白天,其他时间是黑夜。

function switchTheme() {
  const now = new Date();
  const hour = now.getHours();
  const body = document.body;

  if (hour >= 6 && hour < 18) {
    // 白天模式
    body.classList.remove('dark-mode');
    body.classList.add('light-mode');
  } else {
    // 黑夜模式
    body.classList.remove('light-mode');
    body.classList.add('dark-mode');
  }
}

switchTheme(); // 页面加载时立即执行一次

// 每分钟检查一次时间并更新主题
setInterval(switchTheme, 60000); 
body {
  transition: background-color 0.5s ease, color 0.5s ease; /* 添加过渡效果 */
}

.light-mode {
  background-color: white;
  color: black;
}

.dark-mode {
  background-color: black;
  color: white;
}

方法二:根据地理位置和日出日落时间切换

这种方法更精确,它利用用户的地理位置获取日出和日落时间,从而更准确地判断白天和黑夜。你需要使用第三方 API,例如 Sunrise-Sunset API (https://sunrise-sunset.org/api)。

function getSunriseSunset(latitude, longitude) {
  const apiUrl = `https://api.sunrise-sunset.org/json?lat=${latitude}&lng=${longitude}&formatted=0`;

  fetch(apiUrl)
    .then(response => response.json())
    .then(data => {
      const sunrise = new Date(data.results.sunrise);
      const sunset = new Date(data.results.sunset);

      switchThemeBySunriseSunset(sunrise, sunset);

      // 每天更新一次日出日落时间
      setTimeout(() => getSunriseSunset(latitude, longitude), 86400000); // 24 小时
    })
    .catch(error => console.error('Error fetching sunrise/sunset data:', error));
}

function switchThemeBySunriseSunset(sunrise, sunset) {
  const now = new Date();
  const body = document.body;

  if (now >= sunrise && now < sunset) {
    // 白天模式
    body.classList.remove('dark-mode');
    body.classList.add('light-mode');
  } else {
    // 黑夜模式
    body.classList.remove('light-mode');
    body.classList.add('dark-mode');
  }
}


// 获取用户地理位置
navigator.geolocation.getCurrentPosition(position => {
  const latitude = position.coords.latitude;
  const longitude = position.coords.longitude;
  getSunriseSunset(latitude, longitude);
}, error => {
  console.error('Error getting location:', error);
  // 如果获取位置失败,则使用基于时间的切换方法
  switchTheme();
  setInterval(switchTheme, 60000);
});

CSS 代码与方法一相同。

一些额外的建议:

  • 用户设置优先: 提供一个开关让用户手动选择主题,覆盖自动切换功能。
  • 本地存储: 将用户的主题选择存储在 localStorage 中,以便下次访问时保留用户的偏好。
  • 过渡效果: 使用 CSS transition 属性,使主题切换更加平滑。
  • 颜色选择: 选择合适的颜色组合,确保在白天和黑夜模式下都具有良好的可读性。

希望以上信息能帮助你实现所需功能。 选择哪种方法取决于你的需求和项目的复杂程度。 如果只需要简单的根据时间切换,第一种方法就足够了。 如果需要更精确的切换,则可以选择第二种方法。 记住要处理获取地理位置失败的情况。

posted @ 2024-12-03 09:03  王铁柱6  阅读(68)  评论(0编辑  收藏  举报