调用天气预报接口做个动态的网站天气背景
阅读次今天天气特别,有暴雨,上午写代码突发奇想,随手写了段根据天气换背景的代码,不吝啬,分享给大家,基于jQuery的:
function forweather() {
/*调用新浪的免费天气预报接口,其它接口自行更换*/
$.getScript('http://php.weather.sina.com.cn/iframe/index/w_cl.php?code=js&day=0&city=&dfc=1&charset=utf-8', function() {
var s = "",
r = "",
q = "";
for (s in window.SWther.w) {
q = SWther.w[s][0]
}
wtherimg(q.s1)
})
};
function wtherimg(imgsrc) {
/*定义一组天气情况*/
var wth01 = '晴',
wth02 = '多云',
wth03 = '晴转多云',
wth04 = '阴',
wth05 = '小雨',
wth06 = '中雨',
wth07 = '大雨',
wth08 = '暴雨',
wth09 = '雷阵雨',
wth10 = '阵雨',
wth11 = '暴风',
wth12 = '台风',
wth13 = '雾',
wth14 = '霾',
wth15 = '扬沙',
wth16 = '浮尘',
wth17 = '小雪',
wth18 = '中雪',
wth19 = '大雪',
wth20 = '暴风雪';
/*根据天气情况给元素指定不同的图片,当然如果换成H5动画也是可以的,转变想法,把图片换成添加不同的动画原件,就可以实现动态效果了*/
if (imgsrc == wth02) {
$("#demo-canvas").attr("src", "weather/02.jpg")
} else if (imgsrc == wth03) {
$("#demo-canvas").attr("src", "weather/03.jpg")
} else if (imgsrc == wth04) {
$("#demo-canvas").attr("src", "weather/04.jpg")
} else if (imgsrc == wth05) {
$("#demo-canvas").attr("src", "weather/05.jpg")
} else if (imgsrc == wth06) {
$("#demo-canvas").attr("src", "weather/06.jpg")
} else if (imgsrc == wth07) {
$("#demo-canvas").attr("src", "weather/07.jpg")
} else if (imgsrc == wth08) {
$("#demo-canvas").attr("src", "weather/08.jpg")
} else if (imgsrc == wth09) {
$("#demo-canvas").attr("src", "weather/09.jpg")
} else if (imgsrc == wth10) {
$("#demo-canvas").attr("src", "weather/10.jpg")
} else if (imgsrc == wth11) {
$("#demo-canvas").attr("src", "weather/11.jpg")
} else if (imgsrc == wth12) {
$("#demo-canvas").attr("src", "weather/12.jpg")
} else if (imgsrc == wth13) {
$("#demo-canvas").attr("src", "weather/13.jpg")
} else if (imgsrc == wth14) {
$("#demo-canvas").attr("src", "weather/14.jpg")
} else if (imgsrc == wth15) {
$("#demo-canvas").attr("src", "weather/15.jpg")
} else if (imgsrc == wth16) {
$("#demo-canvas").attr("src", "weather/14.jpg")
} else if (imgsrc == wth17) {
$("#demo-canvas").attr("src", "weather/17.jpg")
} else if (imgsrc == wth18) {
$("#demo-canvas").attr("src", "weather/18.jpg")
} else if (imgsrc == wth19) {
$("#demo-canvas").attr("src", "weather/19.jpg")
} else if (imgsrc == wth20) {
$("#demo-canvas").attr("src", "weather/19.jpg")
};
$("#demo-canvas").attr({
"alt": imgsrc,
"title": "当前天气:" + imgsrc + ""
})
};
forweather();
最后在页面底层放上一张图片,绝对定位,搞定。
<img src="weather/sun.png" id="demo-canvas" alt=""/>
当然,你要写成网站的背景也可以,自己改下方法吧。