【问题标题】:Fade in whole div containing multiple divs淡入包含多个 div 的整个 div
【发布时间】:2022-08-05 16:28:02
【问题描述】:

我正在尝试构建一个天气应用程序来学习 JS。我想通过淡出然后淡入来改变天气统计数据。我似乎无法让它工作,基于我用谷歌搜索它的复杂性,因为我首先使用了“显示:无”来隐藏这些元素.如果这是问题,我应该写什么而不是 \"display:none\"?以及如何进行淡出/生效?如果“显示:无”在这里不是真正的问题,只需回答后一个问题。哪一个让我现在受苦。

这是我在这里的第一篇文章,如果我忘记了什么告诉我,我会将它编辑到帖子中!我会留下一个JSFiddle of my code,这样你就可以运行代码并使运行窗口更大。如果您出于某种原因想在这里阅读代码而不进行测试,这里是其中的某些部分(因为发布整个代码需要很多行)。

HTML

<div class=\"containerStats\" class=\"hidden\">

  <p id=\"bigPadding\">Look up a city for it\'s weather stats.</p>

  <div id=\"divTemperature\" class=\"hidden\">

    <p id=\"temperature\">19°</p>
    <p id=\"metricCelcius\">C</p>

  </div>

  <div class=\"hidden\">

    <p id=\"city\">Rosario</p>

    <div id=\"iconText\">

      <p id=\"weatherText\">Sunny</p>
      <img id=\"weatherIcon\" src=\"http://openweathermap.org/img/wn/01d@2x.png\" alt=\"\">

    </div>
  </div>

  <div id=\"spaceBetween\" class=\"hidden\">

    <div>

      <p id=\"windSpeed\"> Wind</p>
      <p id=\"humidity\">Humidity</p>

    </div>

    <div>

      <p id=\"windSpeedKM\"> 32km/h</p>
      <p id=\"humidityPorcentage\">62%</p>

    </div>
  </div>



</div>

CSS

.containerStats {

  display: flex;
  position: absolute;
  bottom: 22px;
  margin: 20px;
  margin-left: 28px;
  padding: 10px;
  text-align: left;
  align-items: center;
  justify-content: space-around;
  background-color: rgba(34, 32, 32, 0.253);
  backdrop-filter: blur(12px);
  border-radius: 10px;


}

#divTemperature {

  display: flex;
  vertical-align: baseline;
}

#temperature {

  font-size: 82px;
  vertical-align: bottom;
}

#metricCelcius {

  font-size: 62px;
  font-weight: 300;
  margin-right: 22px;
  vertical-align: center;
}


#spaceBetween {

  display: flex;
  justify-content: space-between;
  margin-left: 2vw;
}

#windSpeedKM {

  margin-left: 4vw;
}

#humidityPorcentage {

  margin-left: 4vw;
}

.hidden {

  display: none !important;
  opacity: 0;

  transition: 1s;

}

.show {

  transition: 1s;
  opacity: 1;
}

#bigPadding {

  padding: 25px;
}

JS(全部)

//Var declarations for search bar.
let inputCity = document.getElementById(\"searchBar\");
let cityName = inputCity.value;
let searchIcon = document.getElementById(\"searchIcon\");
let recentCitySearches = document.querySelectorAll(\"p.recentCity\");

//Var declarations for stats output.
let temperatureOutput = document.getElementById(\"temperature\");
let cityOutput = document.getElementById(\"city\");
let iconOutput = document.getElementById(\"weatherIcon\");
let adjectiveOutput = document.getElementById(\"weatherText\");
let windOutput = document.getElementById(\"windSpeedKM\");
let humidityOutput = document.getElementById(\"humidityPorcentage\");


//API link-creation vars
let api_url = \"https://api.openweathermap.org/data/2.5/weather?q=\";
let api_key = \"&appid=8d6d613f6cb4621a5c237a580219c44c\";
let unit = \"&units=metric\";


let i = 0;
let start = true;
let finishedStatsChange = true;


//Send input to by pressing enter.
inputCity.addEventListener(\"keydown\", enter => {

  if (enter.key == \"Enter\") {

    //Change city name variable, and call function for upper case.
    cityName = inputCity.value;
    let latestSearch = firstUpperCase(cityName);

    //Update history to show the city name.
    recentCitySearches[i].style.opacity = 0;
    recentCitySearches[i].innerHTML = latestSearch;
    recentCitySearches[i].style.opacity = 1;

    //Clean input text.
    inputCity.value = \"\";
    cityName = latestSearch;
    i++;

    //Finish api url by adding the city name from input, call getData() function-
    let full_url = api_url + cityName + unit + api_key;
    getData(full_url);

    if (i > 2) {

      i = 0;


    }
  }

})

//Send input to by clicking search icon instead of pressing enter.
searchIcon.addEventListener(\"click\", search => {


  //Change city name variable, and call function for upper case.
  cityName = inputCity.value;
  let latestSearch = firstUpperCase(cityName);

  //Update history to show the city name.

  recentCitySearches[i].style.opacity = 0;
  recentCitySearches[i].innerHTML = latestSearch;
  recentCitySearches[i].style.opacity = 1;

  //Clean input text.
  inputCity.value = \"\";
  i++;
  cityName = latestSearch;

  //Finish api url by adding the city name from input, call getData() function-
  let full_url = api_url + cityName + unit + api_key;
  getData(full_url);

  //Execute hideShow()
  hideShow();


  if (i > 2) {

    i = 0;


  }
})

//Function always make first letter upper case.
function firstUpperCase(cityName) {

  //Assign touppercase() to first letter of string, then add the rest of the sentence by using the actual sentence with the first letter sliced. 
  latestSearch = cityName[0].toUpperCase() + cityName.slice(1);

  return latestSearch;

}

//Click a city from history and see its weather again. (City 1)
recentCitySearches[0].addEventListener(\"click\", clickHistory => {

  cityName = recentCitySearches[0].innerText;
  let full_url = api_url + cityName + unit + api_key;
  getData(full_url);



})

//Click a city from history and see its weather again. (City 2)
recentCitySearches[1].addEventListener(\"click\", clickHistory => {

  cityName = recentCitySearches[1].innerText;
  let full_url = api_url + cityName + unit + api_key;
  getData(full_url);

})

//Click a city from history and see its weather again. (City 3)
recentCitySearches[2].addEventListener(\"click\", clickHistory => {

  cityName = recentCitySearches[2].innerText;
  let full_url = api_url + cityName + unit + api_key;
  getData(full_url);

})

//Hide initial message and show weather stats.
function hideShow() {

  if (start == true) {

    let statsHidden = document.querySelectorAll(\".hidden\");

    for (let i = 0; i < statsHidden.length; i++) {

      statsHidden[i].classList.replace(\'hidden\', \'show\');

    }

    let initialMessage = document.getElementById(\"bigPadding\");
    initialMessage.classList.add(\"hidden\");
  }

  start = false;

}


//Change background img depending on city.


//Get info with API.
async function getData(full_url) {

  const api_respone = await fetch(full_url);
  const data = await api_respone.json();

  //Save stats in vars.
  const cityTemperature = data.main.temp;
  const cityHumidity = data.main.humidity;
  const cityWindSpeed = data.wind.speed;
  const weatherAdjective = data.weather[0].description;
  const weatherIcon = data.weather[0].icon;
  changeOutput(cityTemperature, cityHumidity, cityWindSpeed, weatherAdjective, weatherIcon);

  //Once all stats are replaced, execute hideShow()
  hideShow();

}


//Change weather stats info depending on city
function changeOutput(cityTemperature, cityHumidity, cityWindSpeed, weatherAdjective, weatherIcon) {

  temperatureOutput.innerText = Math.round(cityTemperature) + \"°\";
  cityOutput.innerText = cityName;
  iconOutput.src = \"http://openweathermap.org/img/wn/\" + weatherIcon + \"@2x.png\";
  adjectiveOutput.innerText = firstUpperCase(weatherAdjective);
  humidityOutput.innerText = Math.round(cityHumidity) + \"%\";
  windOutput.innerText = Math.round(cityWindSpeed * 3.6) + \"km/h\";

  finishedStatsChange = true;

}

    标签: javascript html css


    【解决方案1】:

    因此,在让它工作的同时,我发现了一些可能在您的 html 中让您感到困惑的不良做法:

    • 将一个 div 声明为多个类,千万不要这样做
    • 将嵌套的 div 声明为相同的类,在某些情况下这是可以的,但出于您的目的,这是不正确的

    所以我在你的 html 中修复了这些,然后添加了一些额外的 css 以继续以前的样式:

    .containerStats {left: 22px;}
    
    .hidden {
      opacity: 0;
      -webkit-transition: all 1s ease-in-out;
      -moz-transition: all 1s ease-in-out;
      -o-transition: all 1s ease-in-out;
      transition: all 1s ease-in-out;
    }
    
    .show {
      opacity: 1;
      -webkit-transition: all 1s ease-in-out;
      -moz-transition: all 1s ease-in-out;
      -o-transition: all 1s ease-in-out;
      transition: all 1s ease-in-out;
    }
    

    然后为了使包含天气统计的html div随着我们放入的css淡入和淡出,我们需要淡出html块,等待动画然后淡入。这最好通过a来实现新的函数调用和对先前函数的更改以将它们链接在一起。

    async function getData(full_url) {
      // get data
      animateChangeOutput(cityTemperature, cityHumidity, cityWindSpeed, weatherAdjective, weatherIcon);
    }
    
    function animateChangeOutput(cityTemperature, cityHumidity, cityWindSpeed, weatherAdjective, weatherIcon) {
        weatherStats = document.getElementById('weatherStats');
      weatherStats.setAttribute('class', 'hidden');
      
      if (i == 1){
        changeOutput(cityTemperature, cityHumidity, cityWindSpeed, weatherAdjective, weatherIcon)
      }else {
        setTimeout(() => { changeOutput(cityTemperature, cityHumidity, cityWindSpeed, weatherAdjective, weatherIcon); }, 1000);
      }
      
      setTimeout(() => {  weatherStats.setAttribute('class', 'show'); }, 1000);
    }
    

    我觉得整个页面都可以进行重组,让这些工作变得更简单、更容易,但这是我能做的最好的事情,而无需对你所做的任何事情进行重大更改

    完整的 JSFiddle 可以在这里找到https://jsfiddle.net/q59n37rx/

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2023-04-04
      • 2013-04-09
      • 2012-07-08
      • 1970-01-01
      • 2014-03-27
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多