如何根据时间自动更改CSS类?

时间:2019-06-30 22:49:07

标签: javascript

我正在构建一个天气应用程序,其中有白天模式和夜间模式。时间根据用户搜索城市的时间而变化。我试图使用此代码在夜间模式和白天模式的不同CSS之间切换

function getMode(response) {
  let today = response.data.dt;
  let timezone = response.data.timezone;
  let difference = today + timezone - 3600;
  let hours = timeConverter2(difference);
  let mode = document.getElementById("app");
  if (hours > 17 || hours < 6) {
    mode.classList.add("darkmode").remove("lightmode");
  }
  if (hours < 17 || hours > 6) {
    mode.classList.add("lightmode").remove("darkmode");
  }
}

其中“ app”是我将类“ lightmode”放在HTML文件中的位置,如下所示:

<body>
    <div id="app" class="lightmode">

(它包装了我的整个代码)。

问题是当我应该更改当前时间时它会变为暗模式,但是当我搜索仍是白天的城市时,尽管小时变量是来自当地时间。

从JavaScript更改CSS将会是一场噩梦,因为有很多很多的类需要使用许多参数进行更改。

我没有看到任何建议或错误吗?

我在此处添加了一个具有HTML,CSS和Javascript的可重现的最小示例:

function search(city) {
  let apiKey = "fe5b1ec1d3199b1c1bb7ae3cbda78fc9";
  let url = `https://api.openweathermap.org/data/2.5/weather?q=${city}&units=metric&appid=${apiKey}`;
  axios.get(url).then(currentCity);
  axios.get(url).then(todayDate);
  axios.get(url).then(todayTime);
  axios.get(url).then(getMode);
}

function handleSubmit(event) {
  event.preventDefault();
  let input = document.querySelector("#keyword");
  search(input.value);
}

let form = document.querySelector("form");
form.addEventListener("submit", handleSubmit);

search("Lisbon,pt");

function currentCity(response) {
  let city = document.querySelector(".current-city");
  let place = response.data.name;
  city.innerHTML = `${place}`;
}

function todayDate(response) {
  let today = response.data.dt;
  let timezone = response.data.timezone;
  let difference = today + timezone - 3600;
  let date = document.querySelector(".date");
  date.innerHTML = timeConverter(difference);
}

function todayTime(response) {
  let time = response.data.dt;
  let timezone = response.data.timezone;
  let difference = time + timezone - 3600;
  let timeToday = document.querySelector(".time");
  timeToday.innerHTML = timeConverter4(difference);
}

function timeConverter(epoch) {
  let a = new Date(epoch * 1000);
  let months = [
    "Jan",
    "Feb",
    "Mar",
    "Apr",
    "May",
    "Jun",
    "Jul",
    "Aug",
    "Sep",
    "Oct",
    "Nov",
    "Dec"
  ];
  let month = months[a.getMonth()];
  let date = a.getDate();
  let time = `${month} ${date}`;
  return time;
}

function timeConverter2(epoch) {
  let a = new Date(epoch * 1000);
  let hour = a.getHours();
  let time = `${hour}`;
  return time;
}

function timeConverter4(epoch) {
  let a = new Date(epoch * 1000);
  let hour = a.getHours();
  let minutes = a.getMinutes();
  if (minutes < 10) {
    minutes = `0${minutes}`;
  }
  let time = `${hour}:${minutes}`;
  return time;
}

function getMode(response) {
  let today = response.data.dt;
  let timezone = response.data.timezone;
  let difference = today + timezone - 3600;
  let hours = timeConverter2(difference);
  let mode = document.getElementById("app");
  if (hours > 20 || hours < 6) {
    mode.classList.add("darkmode").remove("lightmode");
  } else {
    mode.classList.add("lightmode").remove("darkmode");
  }
}
.lightmode h1 {
  font-family: "Josefin Sans", sans-serif;
  text-align: right;
  color: #06384d;
  font-size: 32px;
  font-weight: 700;
}

.lightmode {
  font-family: "Josefin Sans", sans-serif;
  background-image: linear-gradient(120deg, #a1c4fd 0%, #c2e9fb 100%);
  border-style: solid;
  border-radius: 30px;
  border-color: #096386;
}

#app {
  margin: 10px 400px;
  padding: 10px 10px;
}

.element {
  display: block;
  text-align: center;
  font-size: 100px;
  position: relative;
  right: 10px;
}

.lightmode .current {
  display: block;
  position: relative;
  left: 100px;
  top: 5px;
  font-size: 35px;
  font-weight: 600;
  color: #06384d;
}

.lightmode .current-city {
  display: block;
  text-align: center;
  font-size: 32px;
  font-weight: 600;
  color: #06384d;
}

.lightmode .date {
  display: block;
  text-align: center;
  font-size: 25px;
  font-weight: 600;
  color: #06384d;
}

.lightmode .time {
  display: block;
  text-align: center;
  position: relative;
  bottom: 15px;
  font-size: 20px;
  font-weight: 600;
  color: #06384d;
}

.darkmode h1 {
  font-family: "Josefin Sans", sans-serif;
  text-align: right;
  color: #fff;
  font-size: 32px;
  font-weight: 700;
}

.darkmode {
  font-family: "Josefin Sans", sans-serif;
  background-image: linear-gradient(to top, #30cfd0 0%, #330867 100%);
  border-style: solid;
  border-radius: 30px;
  border-color: #096386;
}

.darkmode .current {
  display: block;
  position: relative;
  left: 100px;
  top: 5px;
  font-size: 35px;
  font-weight: 600;
  color: #fff;
}

.darkmode .current-city {
  display: block;
  text-align: center;
  font-size: 32px;
  font-weight: 600;
  color: #fff;
}

.darkmode .date {
  display: block;
  text-align: center;
  font-size: 25px;
  font-weight: 600;
  color: #fff;
}

.darkmode .time {
  display: block;
  text-align: center;
  position: relative;
  bottom: 15px;
  font-size: 20px;
  font-weight: 600;
  color: #fff;
}
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous" />
<link href="https://fonts.googleapis.com/css?family=Josefin+Sans&display=swap" rel="stylesheet" />

<div id="app" class="lightmode">
  <div class="container">
    <h1>WeatherWatch</h1>
    <div class="input-group mb-3">
      <form>
        <input type="text" class="form-control" id="keyword" placeholder="Search city..." aria-label="Input city" aria-describedby="button-addon2" autocomplete="off" />
        <div class="input-group-append">
          <submit class="btn btn-outline-secondary search-btn" type="button" id="button-addon2">
            Search
          </submit>
      </form>
      </div>
    </div>
    <div class="row">
      <div class="col-6">
        <div class="element">
        </div>
        <span class="current"></span>
      </div>
      <div class="col-6">
        <span class="current-city">Lisbon</span>
        <p class="date"></p>
        <p class="time"></p>
      </div>
    </div>

2 个答案:

答案 0 :(得分:2)

我认为问题出在这里

if (hours > 17 || hours < 6) {
  mode.classList.add("darkmode").remove("lightmode");
}
if (hours < 17 || hours > 6) {
  mode.classList.add("lightmode").remove("darkmode");
}

让我们以凌晨3点为例,两个循环都满足条件。所以应该是这样:

if (hours > 17 || hours < 6) {
  mode.classList.add("darkmode").remove("lightmode");
}
else {
  mode.classList.add("lightmode").remove("darkmode");
}

您还应该检查边缘情况:

if (hours >= 6 && hours <= 17) {
  mode.classList.add("lightmode").remove("darkmode");
}
else {
  mode.classList.add("darkmode").remove("lightmode");
}

答案 1 :(得分:0)

为了解决类似问题的人的利益,我只是以这种方式更改了代码的顺序:

<script>
  import Helper from './helper.js';
  let helper = new Helper();
</script>

<h1>Hello</h1>

并有最后一行

if (hours > 17) {
    mode.classList.add("darkmode").remove("lightmode");
  }
  if (hours < 6) {
    mode.classList.add("darkmode").remove("lightmode");
  } else {
    mode.classList.remove("darkmode").add("lightmode");
  }
}

代替

mode.classList.remove("darkmode").add("lightmode");