jquery 根据温度范围改变背景颜色

xuo3flqw  于 5个月前  发布在  jQuery
关注(0)|答案(2)|浏览(79)

我正在从Weather Underground获得一些API信息,想知道是否有可能通过jQuery使用API提供的信息来更改整个body的背景颜色。
我想做的是基于通过API返回的特定范围的Temperature在body标记上设置一个类。例如:

"current_observation": {
    "image": {
    "url":"http://icons-ak.wxug.com/graphics/wu2/logo_130x80.png",
    "title":"Weather Underground",
    "link":"http://www.wunderground.com"
    },
    "display_location": {
    "full":"Bowling Green, KY",
    "city":"Bowling Green",
    "state":"KY",
    "state_name":"Kentucky",
    "country":"US",
    "country_iso3166":"US",
    "zip":"42101",
    "latitude":"37.02899933",
    "longitude":"-86.46366119",
    "elevation":"154.00000000"
    },
    "observation_location": {
    "full":"Ridgeview Drive, Bowling Green, Kentucky",
    "city":"Ridgeview Drive, Bowling Green",
    "state":"Kentucky",
    "country":"US",
    "country_iso3166":"US",
    "latitude":"36.993744",
    "longitude":"-86.522827",
    "elevation":"714 ft"
    },
    "estimated": {
    },
    "station_id":"KKYBOWLI7",
    "observation_time":"Last Updated on May 24, 2:25 PM CDT",
    "observation_time_rfc822":"Thu, 24 May 2012 14:25:18 -0500",
    "observation_epoch":"1337887518",
    "local_time_rfc822":"Thu, 24 May 2012 14:25:29 -0500",
    "local_epoch":"1337887529",
    "local_tz_short":"CDT",
    "local_tz_long":"America/Chicago",
    "local_tz_offset":"-0500",
    "weather":"Clear",
    "temperature_string":"86.8 F (30.4 C)",
    "temp_f":86.8

字符串
这是我收集的一些信息。最后一个temp_f是我想关注的。
范围示例为- 80到90应显示background:#dd7f35
我尝试过设置自定义变量,但总是搞砸了。我似乎不知道如何使用从JSON中提取的信息来设置变量(如果可能的话,因为temp_f使用小数)。
下面是我如何调用JSON

$().ready(function(){ 
    $.getJSON("http://api.wunderground.com/api/[MY API KEY]/conditions/q/autoip.json?callback=?",
    function(data){
        $.each(data, function(i, json) {
        content = '<h1>' + json.icon + '</h1>';
        content += '<img src=' + json.icon_url +'>';
        content += '<p>' + json.temp_f + '<p>';
        $(content).appendTo("#area");
        });
    console.log(data)
    });
});


这是我尝试过的

var backDrop = ' + json.temp_f + '


我使用+ json.temp_f +,因为这是拉在临时刚刚好的常规HTML,但我可以假设,这是不会在这种情况下工作?
任何帮助都非常感谢。

qyzbxkaa

qyzbxkaa1#

var backDrop = json.temp_f;

字符串
把引号和加号去掉。
或者你可以这样做:

var colorOutput = '';

 if(json.temp_f < 20){
     colorOutput = 'blue'; //use hex color
 }else if(json.temp_f >=20 && json.temp_f < 60){
     colorOutput = 'orange'; //use hex color
 }

 $('#colorMeElement').css('background',colorOutput);

y3bcpkx1

y3bcpkx12#

为每个范围-颜色组合设置CSS样式,例如具有背景的.range_80_90:#dd7f35。然后您可以在脚本中动态创建类并将其应用于适当的元素。

相关问题