[英]how can i swap between two icons?
我是 JavaScript 的新手,我正在制作一個天氣應用程序,它運行良好,但問題出在圖標上,當我輸入另一個國家/地區查看天氣時,新的國家/地區圖標位於前一個國家/地區圖標之上,我想隱藏上一個圖標並顯示新圖標 我嘗試了 if 語句和 switch case 方法,但它不起作用
這是我的 html 代碼:
<form>
<input class="input" type="text" placeholder="type your country">
</form>
<button class="button">SUBMIT</button>
<div class="location">
<h1 class="timezone">TIMEZONE</h1>
<div id="icons" class="">
<img id="cloud" class="hide" src="./gifs/cloud.png">
<img id="clouds" class="hide" src="./gifs/clouds.png">
<img id="cloudy" class="hide" src="./gifs/cloudy.png">
<img id="rain" class="hide" src="./gifs/rain.png">
<img id="snowflake" class="hide" src="./gifs/snowflake.png">
<img id="storm" class="hide" src="./gifs/storm.png">
<img id="sun" class="hide" src="./gifs/sun.png">
<img id="wind" class="hide" src="./gifs/wind.png">
</div>
</div>
這是我的 javascript 代碼:
const temp = data.main.temp - 273.15 ;
const celsius = temp.toPrecision(3);
const descripiton = data.weather[0].description;
const name = data.name;
tempDeg.textContent = celsius;
tempDes.textContent = descripiton;
tmZn.textContent = name;
switch(descripiton){
case "mist" :
document.getElementById("wind").classList.remove("hide");
break;
case "clear sky" :
document.getElementById("sun").classList.remove("hide");
break;
case "broken clouds" :
document.getElementById("clouds").classList.remove("hide");
break;
case "shower rain" :
document.getElementById("rain").classList.remove("hide");
break;
case "thunderstorm" :
document.getElementById("storm").classList.remove("hide");
break;
case "snow" :
document.getElementById("snow").classList.remove("hide");
break;
case "few clouds" :
document.getElementById("cloudy").classList.remove("hide");
break;
case "scattered clouds" :
document.getElementById("cloud").classList.remove("hide");
break;
}
您需要使用for
循環之類的東西隱藏所有內容。
var icons = document.querySelector("#icons").children;
for (var i=0; i<icons.length; i++) {
icons[i].classList.add("hide");
}
然后從您希望顯示的代碼中刪除隱藏 class,就像您在代碼中所做的那樣。
如果您只顯示一個圖標,還有另一種方法,而不是隱藏所有圖標
var iconName = 'default'
switch(descripiton) {
case "mist" :
iconName = 'wind';
break;
case "clear sky" :
iconName = 'sun';
break;
case "broken clouds" :
iconName = 'clouds'
break;
// add rest of items here
}
document.getElementById("icons").innerHTML = '<img src="./gifs/' + iconName + '.png">';
如果您想保留當前方法,請先隱藏所有圖標,然后僅顯示所需的圖標
var images = document.getElementById('icons').querySelectorAll('img');
for (i = 0; i < images.length; i++){
images[i].classList.add('hide');
}
在您的開關中,使相關項目像這樣可見
document.getElementById("wind").classList.remove("hide");
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.