【问题标题】:js background change depends on weather condition (code not working)js 背景变化取决于天气状况(代码不起作用)
【发布时间】:2021-07-07 02:31:09
【问题描述】:

尽管“Categoryvalue”中有数据,但条件不起作用。我只是 JS 的新手。 我的方法错了吗?如何根据天气情况改变背景?

var button = document.querySelector('.button')
var inputValue = document.querySelector('.inputValue')
var name1 = document.querySelector('.name1');
var desc = document.querySelector('.desc');
var temp = document.querySelector('.temp'); 
var category = document.querySelector('.category'); 

button.addEventListener('click',function(){
    fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputValue.value+'&appid=<removed>')
    .then(response => response.json()) 
    // .then(data => console.log(data))
    .then(data => {
        var nameValue = data['name'];
        var categoryValue =data['weather'][0]['main'];
        var tempValue = data['main']['temp'];
        var descValue = data['weather'][0]['description'];
        var tofloat = Math.abs(tempValue - 273.15);
        var tempCelcius= parseFloat(tofloat).toFixed(2);

        name1.innerHTML = nameValue;
        category.innerHTML = categoryValue;
        temp.innerHTML = tempCelcius;
        desc.innerHTML = descValue;

        if(categoryValue == 'Clear'){
            document.body.style.backgroundImage =url('../pictures/clear.jpg');
        }else if(categoryValue == 'Clouds'){
            document.body.style.backgroundImage =url('../pictures/clouds.jpg');
        }else if(categoryValue == 'Rain'){
            document.body.style.backgroundImage = url("../pictures/rain.jpg");
        }
    })
.catch(err => alert("Wrong City Name!"))
})

【问题讨论】:

  • 问题出在哪里?你改变背景的方式,或者你在下雨时获取信息的方式?
  • 我更改背景图像的方式。在 if else 条件下
  • 添加console.log(categoryValue)
  • nvm,我知道是什么问题了,我一会儿写出来
  • 好像已经有2个人回答了,我就不写了

标签: javascript openweathermap


【解决方案1】:

更改body元素背景图片时,必须将document.body.style.backgroundImage的值设置为字符串。否则,您正在调用名称为 url 的函数,该名称不存在,因此会引发错误。因此,您的条件代码将是这样的:

    if (categoryValue == 'Clear') {
        document.body.style.backgroundImage = 'url("../pictures/clear.jpg")';
    } else if(categoryValue == 'Clouds'){
        document.body.style.backgroundImage = 'url("../pictures/clouds.jpg")';
    } else if(categoryValue == 'Rain'){
        document.body.style.backgroundImage = 'url("../pictures/rain.jpg")';
    }

【讨论】:

    【解决方案2】:

    你忘了用 qoutes 包围 url()

        if(categoryValue == 'Clear'){
            document.body.style.backgroundImage = "url('../pictures/clear.jpg')";
        }else if(categoryValue == 'Clouds'){
            document.body.style.backgroundImage = "url('../pictures/clouds.jpg')";
        }else if(categoryValue == 'Rain'){
            document.body.style.backgroundImage = "url('../pictures/rain.jpg')";
        }
    

    但我建议避免使用内联样式并通过 CSS 更改它,如下所示:

    var button = document.querySelector('.button')
    var inputValue = document.querySelector('.inputValue')
    var name1 = document.querySelector('.name1');
    var desc = document.querySelector('.desc');
    var temp = document.querySelector('.temp'); 
    var category = document.querySelector('.category'); 
    
    button.addEventListener('click',function(){
        fetch('https://api.openweathermap.org/data/2.5/weather?q='+inputValue.value+'&appid=' +document.getElementById("api").value)
        .then(response => response.json()) 
        // .then(data => console.log(data))
        .then(data => {
            var nameValue = data['name'];
            var categoryValue =data['weather'][0]['main'];
            var tempValue = data['main']['temp'];
            var descValue = data['weather'][0]['description'];
            var tofloat = Math.abs(tempValue - 273.15);
            var tempCelcius= parseFloat(tofloat).toFixed(2);
    
            name1.innerHTML = nameValue;
            category.innerHTML = categoryValue;
            temp.innerHTML = tempCelcius;
            desc.innerHTML = descValue;
    
            document.body.setAttribute("category", categoryValue);
    /*
            if(categoryValue == 'Clear'){
                document.body.style.backgroundImage = "url('../pictures/clear.jpg')";
            }else if(categoryValue == 'Clouds'){
                document.body.style.backgroundImage = "url('../pictures/clouds.jpg')";
            }else if(categoryValue == 'Rain'){
                document.body.style.backgroundImage = "url('../pictures/rain.jpg')";
            }
    */
         })
    .catch(err => alert("Wrong City Name!"))
    })
    body[category="Clear"]
    {
      background-image: url('../pictures/clear.jpg');
      background-color: lightblue;
    }
    body[category="Clouds"]
    {
      background-image: url('../pictures/clouds.jpg');
      background-color: silver;
    }
    body[category="Rain"]
    {
      background-image: url('../pictures/rain.jpg');
      background-color: dimgray;
    }
    
    
    body[category="Clear"] .category
    {
      background-color: blue;
      color: white;
    }
    body[category="Clouds"] .category
    {
      background-color: dimgray;
      color: white;
    }
    body[category="Rain"] .category
    {
      background-color: black;
      color: white;
    }
    <div><a href="https://openweathermap.org/api" target="_blank">API ID</a>: <input id="api"></div>
    City: <input class="inputValue">
    <button class="button">Submit</button>
    
    <div class="name1"></div>
    <div class="desc"></div>
    <div class="temp"></div>
    <div class="category"></div>

    使用这种方法不仅可以更好地控制样式,而且如果存在“未知”类别,它会自动回退到默认样式。

    【讨论】:

    • 谢谢各位大师,解决了我的问题。
    猜你喜欢
    • 2017-11-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-12
    • 2021-09-17
    • 1970-01-01
    • 2011-08-25
    相关资源
    最近更新 更多