精华内容
下载资源
问答
  • 原生JS实现天气预报

    2020-11-20 03:44:06
    本文实例为大家分享了JS实现天气预报的具体代码,供大家参考,具体内容如下 HTML代码 <!doctype html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content...
  • js实现天气预报 很实用 js实现天气预报 很实用
  • JS实现天气预报查询

    千次阅读 2018-12-19 18:01:41
    样品展示 HTML &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head lang="en"...全国天气查询小应用&lt;/title&gt; &lt;link rel="stylesheet" h

    样品展示
    在这里插入图片描述

    HTML

    <!DOCTYPE html>
    <html>
    <head lang="en">
        <meta charset="UTF-8">
        <title>全国天气查询小应用</title>
        <link rel="stylesheet" href="weather.css"/>
        <link rel="icon" href="favicon.ico"/>
    	
    </head>
    <body>
    <audio  autoplay loop="loop">
    	<source src="mp3/海为气象园.mp3">
    </audio>
    
    <header>
        <h1><font face='cursive' color='white'><b>❄ 海为气象园 ❄</b></font></h1>
        <div id="weather_search">
            <span><input id="text" type="text" placeholder="请输入您要查询的城市" /></span>
            <span><input id="btn" type="button" value=" 查询天气" /></span>
        </div>
    </header>
        <section>
    	<font color='white'>
            <div id="today_container">
    		
                <div>
                    <img src="./images/weather_icon/1.png" alt="今日天气"/>
                </div><p><font size='30'color='white'><b>☀ ☁ ☂ ❄</b></font></p>
                <div>
                    <div class="main_info"><span class="info">城市</span>|<span class="info">201X-XX-XX</span>|<span class="info">星期X</span>|<span class="info">---</span> </div>
                    <div class="more_info">今日温度:<span class="info">-----</span>风力:<span class="info">-----</span>风向:<span class="info">-----</span>PM2.5:<span class="info">--</span></div>
                </div>
            </div>
            <div id="future_container">
                <div class="future_box">
                    <img src="./images/weather_icon/1.png" alt="天气"/>
                    <span class="future_info">201X-XX-XX</span>
                    <span class="future_info">星期X</span>
                    <span class="future_info">--</span><span class="future_info">12-16℃</span>
                </div>
                <div class="future_box">
                    <img src="./images/weather_icon/3.png" alt="天气"/>
                    <span class="future_info">201X-XX-XX</span>
                    <span class="future_info">星期X</span>
                    <span class="future_info">--</span><span class="future_info">12-16℃</span>
                </div>
                <div class="future_box">
                    <img src="./images/weather_icon/2.png" alt="天气"/>
                    <span class="future_info">201X-XX-XX</span>
                    <span class="future_info">星期X</span>
                    <span class="future_info">--</span><span class="future_info">12-16℃</span>
                </div>
    			
                <div class="future_box">
                    <img src="./images/weather_icon/4.png" alt="天气"/>
                    <span class="future_info">201X-XX-XX</span>
                    <span class="future_info">星期X</span>
                    <span class="future_info">--</span><span class="future_info">12-16℃</span>
                </div>
                <div class="future_box">
                    <img src="images/weather_icon/5.png" alt="天气"/>
                    <span class="future_info">201X-XX-XX</span>
                    <span class="future_info">星期X</span>
                    <span class="future_info">-</span><span class="future_info">12-16℃</span>
                </div>
    			
            </div>
    	</font>
        </section>
    	
        <footer>
            <div>design and code by zsq</div>
        </footer>
        <script src="index.js"></script>
    	<div style="text-align:center;">
    	
    </div>
    
    </body>
    </html>`在这里插入代码片`
    

    CSS

    body,div,h1,h2,h3,h4,h5,h6,input,header,main,ul,li,footer,p,span,section{
        padding: 0;
        margin: 0;
    }
    html,body{
        height: 100%;
        min-width: 960px;
    }
    body{
        background: url(images/bg.jpg) no-repeat;
        font-size: 14px;
        font-family: "microsoft yahei";
        -webkit-background-size: 100%;
        background-size: 100%;
        color: #222;
    }
    header{
        height: 50px;
        padding-left: 80px;
        background: rgba(100, 100, 100, 0.6);
    }
    h1{
        padding-right: 30px;
        line-height: 50px;
        font-size: 30px;
        float: left;
    }
    #weather_search{
        margin-top: 10px;
        float: left;
    }
    #weather_search span{
        height: 30px;
        float: left;
    }
    #text{
        padding: 0 6px 0 6px;
        background: #fff;
        font-size: 14px;
        width: 240px;
        height: 30px;
        border: none;
        outline: none;
    }
    #btn{
        width: 70px;
        height: 30px;
        border: none;
        background: rgba(255,255,255,0.5);
        color: #333;
        outline: none;
        cursor: pointer;
    }
    #btn:hover{
        background: rgba(255, 255, 255, 0.3);
    }
    section{
        padding-top: 90px;
    }
    #today_container{
        width: 900px;
        margin: 0 auto;
        padding: 20px;
        background: rgba(100,100,100,0.3);
        overflow: hidden;
    }
    #today_container div img {
        margin: 0 50px 0 40px;
        float: left;
    }
     .main_info{
        font-size: 24px;
        margin-bottom: 10px;
    }
     .main_info span{
        margin: 0 15px;
    }
     .main_info span:first-child{
        margin-left: 0;
    }
     .more_info {
        margin-top: 3px;
        font-size: 16px;
    }
     .more_info span{
        margin: 0 15px 0 0;
    }
    #future_container{
        margin: 80px auto 0 auto;
        width: 950px;
        text-align: center;
        overflow: hidden;
    }
    #future_container div{
        float: left;
        width: 150px;
        padding: 20px 0;
        margin: 0 20px;
        background: rgba(100, 100, 100, 0.3);
    }
    #future_container div:hover{
        background: rgba(200,200,200,0.5);
    }
    #future_container div span{
        display: block;
    }
    footer{
        position: absolute;
        bottom: 0;
        width: 100%;
    }
    footer div{
        width: 175px;
        margin: 0 auto;
    }
    

    JS

    /**
     * Created by zsq on 2016/11/13.
     */
    //调用jsonp函数请求当前所在城市
    jsonp('https://api.map.baidu.com/api?v=2.0&ak=Dv1NMU23dh1sGS9n2tUouDEYY96Dfzh3&s=1&callback=getCity');
    window.onload = function () {
        //请求天气车数据
        btn.addEventListener('click',function () {
            jsonp(createUrl()[0]);
            jsonp(createUrl()[1]);
        });
        text.addEventListener('keydown', function (e){
            if (e.keyCode == 13) {
                jsonp(createUrl()[0]);
                jsonp(createUrl()[1]);
            }
        });
    }
    
    function getCity() {
        function city(result) {
            //去掉城市名后的"市"
            var city = result.name.substring(0, result.name.length - 1);
            //请求当前城市的天气数据
            jsonp(createUrl(city)[0]);
            jsonp(createUrl(city)[1]);
        }
        var cityName = new BMap.LocalCity();
        cityName.get(city);
    }
    
    // 数据请求函数
    function jsonp(url) {
        var script = document.createElement('script');
        script.src = url;
        document.body.insertBefore(script, document.body.firstChild);
        document.body.removeChild(script);
    }
    
    //数据请求成功回调函数,用于将获取到的数据放入页面相应位置
    function getWeather(response) {
        var oSpan = document.getElementsByClassName('info');
        var data = response.result;
        oSpan[0].innerHTML = data[0].citynm;
        oSpan[1].innerHTML = data[0].days;
        oSpan[2].innerHTML = data[0].week;
        oSpan[3].innerHTML = data[0].weather;
        oSpan[4].innerHTML = data[0].temperature;
        oSpan[5].innerHTML = data[0].winp;
        oSpan[6].innerHTML = data[0].wind;
    
        var aDiv = document.getElementsByClassName('future_box');
        for (var i = 0; i < aDiv.length; i++) {
            var aSpan = aDiv[i].getElementsByClassName('future_info');
            aSpan[0].innerHTML = data[i + 1].days;
            aSpan[1].innerHTML = data[i + 1].week;
            aSpan[2].innerHTML = data[i + 1].weather;
            aSpan[3].innerHTML = data[i + 1].temperature;
        }
        //根据返回数据,替换不同天气图片
        changeImg(response);
    }
    
    function getTodayWeather(response) {
        var oSpan = document.getElementsByClassName('info');
        var data = response.results;
        oSpan[7].innerHTML = data[0].pm25;
        oSpan[8].innerHTML = data[0].index[4].zs;
        oSpan[9].innerHTML = data[0].index[1].zs;
        oSpan[10].innerHTML = data[0].index[2].zs;
        oSpan[11].innerHTML = data[0].index[0].zs;
    }
    
    //根据获取到的数据更改页面中相应的图片
    function changeImg(data) {
        var firstImg = document.getElementsByTagName("img")[0];
        var firstWeatherId = data.result[0].weatid;
        chooseImg(firstWeatherId, firstImg);
    
        var aImg = document.getElementById('future_container').getElementsByTagName('img');
        for (var j = 0; j < aImg.length; j++) {
            var weatherId = data.result[j + 1].weatid;
            chooseImg(weatherId, aImg[j]);
        }
    }
    
    //选择图片
    function chooseImg(id, index) {
        switch (id) {
            case '1':
                index.src = 'images/weather_icon/1.png';
                break;
            case '2':
                index.src = 'images/weather_icon/2.png';
                break;
            case '3':
                index.src = 'images/weather_icon/3.png';
                break;
            case '4':
            case '5':
            case '6':
            case '8':
            case '9':
            case '10':
            case '11':
            case '12':
            case '13':
            case '20':
            case '22':
            case '23':
            case '24':
            case '25':
            case '26':
                index.src = 'images/weather_icon/4.png';
                break;
            case '7':
                index.src = 'images/weather_icon/6.png';
                break;
            case '14':
            case '15':
            case '16':
            case '17':
            case '18':
            case '27':
            case '28':
            case '29':
                index.src = 'images/weather_icon/5.png';
                break;
            case '19':
            case '21':
            case '30':
            case '31':
            case '32':
            case '33':
                index.src = 'images/weather_icon/7.png';
                break;
            default:
                index.src = 'images/weather_icon/8.png';
        }
    }
    
    //根据城市名创建请求数据及url
    function createUrl() {
        var cityName = '';
        if (arguments.length == 0) {
            cityName = document.getElementById('text').value;
        } else {
            cityName = arguments[0];
        }
        var urls = [];
        urls[0] = 'https://sapi.k780.com/?app=weather.future&appkey=10003&sign=b59bc3ef6191eb9f747dd4e83c99f2a4&format=json&jsoncallback=getWeather&weaid=' + encodeURI(cityName);
        urls[1] = 'https://api.map.baidu.com/telematics/v3/weather?output=json&ak=FK9mkfdQsloEngodbFl4FeY3&callback=getTodayWeather&location=' + encodeURI(cityName);
        return urls;
    }
    
    展开全文
  • 本文主要介绍使用node.js做一个自用的天气插件,需要的朋友可以参考下。
  • type="text" id="city" class="input_txt" placeholder="请输入查询的天气" /> (event)"> 搜 索 button> div> <div class="hotkey"> <a href="javascript:;">北京a> <a href="javascript:;">上海a> <a href="...

    1.css文件:
    <1>index.css

    body {
    	font-family: 'Microsoft YaHei';
    }
    
    .wrap {
    	position: fixed;
    	left: 0;
    	top: 0;
    	width: 100%;
    	height: 100%;
    	/* background: radial-gradient(#f3fbfe, #e4f5fd, #8fd5f4); */
    	/* background:#8fd5f4; */
    	/* background: linear-gradient(#6bc6ee, #fff); */
    	background: #fff;
    
    }
    
    .search_form {
    	width: 640px;
    	margin: 100px auto 0;
    }
    
    .logo img {
    	display: block;
    	margin: 0 auto;
    }
    
    .form_group {
    	width: 640px;
    	height: 40px;
    	margin-top: 45px;
    }
    
    .input_txt {
    	width: 538px;
    	height: 38px;
    	padding: 0px;
    	float: left;
    	border: 1px solid #41a1cb;
    	outline: none;
    	text-indent: 10px;
    }
    
    .input_sub {
    	width: 100px;
    	height: 40px;
    	border: 0px;
    	float: left;
    	background-color: #41a1cb;
    	color: #fff;
    	font-size: 16px;
    	outline: none;
    	cursor: pointer;
    	position: relative;
    }
    
    .input_sub.loading::before {
    	content: '';
    	position: absolute;
    	left: 0;
    	top: 0;
    	width: 100%;
    	height: 100%;
    	background: url('../img/loading.gif');
    }
    
    .hotkey {
    	margin: 3px 0 0 2px;
    }
    
    .hotkey a {
    	font-size: 14px;
    	color: #666;
    	padding-right: 15px;
    }
    
    .weather_list {
    	height: 200px;
    	text-align: center;
    	margin-top: 50px;
    	font-size: 0px;
    }
    
    .weather_list li {
    	display: inline-block;
    	width: 140px;
    	height: 200px;
    	padding: 0 10px;
    	overflow: hidden;
    	position: relative;
    	background: url('../img/line.png') right center no-repeat;
    	background-size: 1px 130px;
    }
    
    .weather_list li:last-child {
    	background: none;
    }
    
    /* .weather_list .col02{
        background-color: rgba(65, 165, 158, 0.8);
    }
    .weather_list .col03{
        background-color: rgba(94, 194, 237, 0.8);
    }
    .weather_list .col04{
        background-color: rgba(69, 137, 176, 0.8);
    }
    .weather_list .col05{
        background-color: rgba(118, 113, 223, 0.8);
    } */
    
    
    .info_date {
    	width: 100%;
    	height: 40px;
    	line-height: 40px;
    	color: #999;
    	font-size: 14px;
    	left: 0px;
    	bottom: 0px;
    	margin-top: 15px;
    }
    
    .info_date b {
    	float: left;
    	margin-left: 15px;
    }
    
    .info_type span {
    	color: #fda252;
    	font-size: 30px;
    	line-height: 80px;
    }
    
    .info_temp {
    	font-size: 14px;
    	color: #fda252;
    }
    
    .info_temp b {
    	font-size: 13px;
    }
    
    .tem .iconfont {
    	font-size: 50px;
    }
    
    

    <2>reset.css

    body,
    ul,
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
    	margin: 0;
    	padding: 0;
    }
    
    h1,
    h2,
    h3,
    h4,
    h5,
    h6 {
    	font-size: 100%;
    	font-weight: normal;
    }
    
    a {
    	text-decoration: none;
    }
    
    ul {
    	list-style: none;
    }
    
    img {
    	border: 0px;
    }
    
    /* 清除浮动,解决margin-top塌陷 */
    .clearfix:before,
    .clearfix:after {
    	content: '';
    	display: table;
    }
    
    .clearfix:after {
    	clear: both;
    }
    
    .clearfix {
    	zoom: 1;
    }
    
    .fl {
    	float: left;
    }
    
    .fr {
    	float: right;
    }
    
    

    2.图片文件
    <1>line.png
    在这里插入图片描述
    <2>logo.png
    在这里插入图片描述

    <!DOCTYPE html>
    <html lang="en">
    
    	<head>
    		<meta charset="UTF-8" />
    		<meta name="viewport" content="width=device-width, initial-scale=1.0" />
    		<meta http-equiv="X-UA-Compatible" content="ie=edge" />
    		<title>天知道</title>
    		<link rel="stylesheet" href="css/reset.css" />
    		<link rel="stylesheet" href="css/index.css" />
    	</head>
    
    	<body>
    		<div class="wrap" id="app">
    			<div class="search_form">
    				<div class="logo"><img src="img/logo.png" alt="logo" /></div>
    				<div class="form_group">
    					<input onkeyup="search(event)" type="text" id="city" class="input_txt" placeholder="请输入查询的天气" />
    					<button class="input_sub" onclick="search(event)">
    						搜 索
    					</button>
    				</div>
    				<div class="hotkey">
    					<a href="javascript:;">北京</a>
    					<a href="javascript:;">上海</a>
    					<a href="javascript:;">广州</a>
    					<a href="javascript:;">深圳</a>
    				</div>
    			</div>
    			<ul class="weather_list" id="myUL">
    				<!-- <li>
    					<div class="info_type"><span class="iconfont">多云</span></div>
    					<div class="info_temp">
    						<b>低温</b>
    						~
    						<b>高温</b>
    					</div>
    					<div class="info_date"><span>日期</span></div>
    				</li> -->
    			</ul>
    		</div>
    
    	</body>
    
    </html>
    <script type="text/javascript">
    	//创建异步请对象
    	var xmlhttp = new XMLHttpRequest();
    	//点击搜索
    	function search(e) {
    		if (e.keyCode == 13 || e.type == 'click') {
    			//发送
    			//获取用户输入的城市名
    			var cityName = document.getElementById("city").value;
    			if (!cityName) {
    				alert("请输入城市名");
    				return; //直接结束掉
    			}
    			xmlhttp.open("GET", "http://wthrcdn.etouch.cn/weather_mini?city=" + cityName, true);
    			xmlhttp.send();
    			//准备接收后台响应的结果
    			xmlhttp.onreadystatechange = function() {
    				if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
    					//获取后台返回的JSON字符串
    					var jsonStr = xmlhttp.responseText;
    					console.log(jsonStr);
    					//把JSON字符串转换成JSON对象
    					var jsonObj = JSON.parse(jsonStr);
    					//解析JSON数据展示到页面
    					var jsonArr = jsonObj.data.forecast;
    					parseJSON(jsonArr);
    				}
    			}
    		}
    	}
    
    	function parseJSON(jsonArr) {
    		var ul = document.getElementById("myUL");
    		//动态的创建li标签,li标签之间的数据,是从json中解析出来的,并且还要li标签放到ul之间
    
    		/* 
    		 <li>
    		 	<div class="info_type"><span class="iconfont">多云</span></div>
    		 	<div class="info_temp">
    		 		<b>低温</b>
    		 		~
    		 		<b>高温</b>
    		 	</div>
    		 	<div class="info_date"><span>日期</span></div>
    		 </li> 
    		 */
    		var li = '';
    		for (var i = 0; i < jsonArr.length; i++) {
    			var jsonEle = jsonArr[i];
    			li += `<li>
    		 	<div class="info_type"><span class="iconfont">${jsonEle.type}</span></div>
    		 	<div class="info_temp">
    		 		<b>${jsonEle.low}</b>
    		 		~
    		 		<b>${jsonEle.high}</b>
    		 	</div>
    		 	<div class="info_date"><span>${jsonEle.date}</span></div>
    		 </li>`
    		}
    
    		ul.innerHTML = li;
    	}
    </script>
    
    

    效果如图:
    在这里插入图片描述

    展开全文
  • 天气预报js插件

    2015-07-03 11:19:31
    web页面第三方天气预报插件-素材目录,js插件
  • -- 天气预报 --> <div class="forecast"> </div> <!-- 生活指数 --> <div class="lifestyle"> 生活指数</h2> <div class="lifestyle-box"> <div class="lifestyle-item" data-indexs="0"> ...

    效果图
    在这里插入图片描述

    HTML代码

    <!doctype html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <meta name="viewport"
              content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
        <meta http-equiv="X-UA-Compatible" content="ie=edge">
        <title>Document</title>
        <link rel="stylesheet" href="tianqi.css">
        <link rel="stylesheet" href="iconfont/iconfont.css">
    </head>
    <body>
            <!--    搜索    -->
        <div class="search">
            <span>Tq</span>
            <form target="sou" id="search_from">
            <input type="search" placeholder="输入搜索的城市">
            <iframe name="sou" style = "display: none"></iframe>
            </form>
            <div class="search-btn"><img src="images/search.png" alt=""></div>
        </div>
            <!--    历史记录-->
        <div class="history">
            <div class="la">
                <span>历史查询</span>
                <img src="images/more.png" alt="">
            </div>
            <div class="historys">
            <!--    历史记录        -->
            </div>
            <div class="clearbtn">
                清除历史记录
            </div>
        </div>
            <!--    今日天气    -->
        <div class="information">
    
        </div>
            <!--    天气预报    -->
        <div class="forecast">
    
        </div>
            <!--    生活指数    -->
        <div class="lifestyle">
                <h2>生活指数</h2>
                <div class="lifestyle-box">
                    <div class="lifestyle-item" data-indexs="0">
                        <i class="iconfont icon-shushidu"></i>
                        <span>舒适度指数</span>
                    </div>
                    <div class="lifestyle-item" data-indexs="1">
                        <i class="iconfont icon-3chuanyixiguan"></i>
                        <span>穿衣指数</span>
                    </div>
                    <div class="lifestyle-item" data-indexs="2">
                        <i class="iconfont icon-ganmaoyaowu"></i>
                        <span>感冒指数</span>
                    </div>
                    <div class="lifestyle-item" data-indexs="3">
                        <i class="iconfont icon-yundong"></i>
                        <span>运动指数</span>
                    </div>
                    <div class="lifestyle-item" data-indexs="4">
                        <i class="iconfont icon-lvyou"></i>
                        <span>旅游指数</span>
                    </div>
                    <div class="lifestyle-item" data-indexs="5">
                        <i class="iconfont icon-iconset0451"></i>
                        <span>紫外线指数</span>
                    </div>
                    <div class="lifestyle-item" data-indexs="6">
                        <i class="iconfont icon-xiche"></i>
                        <span>洗车指数</span>
                    </div>
                    <div class="lifestyle-item" data-indexs="7">
                        <i class="iconfont icon-kongqiwuranfenxi"></i>
                        <span>空气污染扩散条件指数</span>
                    </div>
                </div>
            </div>
            <!--    生活指数弹窗    -->
        <div class="lifestyle-tc">
        </div>
        <script src="rem.js"></script>
        <script src="Ajax.js"></script>
        <script src="tianqi.js"></script>
    </body>
    </html>
    

    CSS代码

    * {
        margin: 0;
        padding: 0;
    }
    ul,li {
        list-style: none;
    }
    body {
        background-size: 120%;
        color: white;
    }
    .search {
        position: fixed;
        width: 100%;
        height: 0.5rem;
        background-color: rgba(0,0,0,.0);
        display: flex;
        justify-content: space-between;
        align-items: center;
    }
    #search_from {
        width: 2.8rem;
        height: 0.4rem;
        position: relative;
    }
    .search > span {
        width: 0.5rem;
        font-size: 0.25rem;
        line-height: 0.5rem;
        text-align: center;
        font-family: "Segoe UI Symbol";
        color: white;
    }
    .search #search_from > input {
        width: 2.8rem;
        height: 0.4rem;
        border-radius: 0.1rem;
        text-indent: 0.1rem;
        outline: none;
        position: absolute;
        border: none;
        border-bottom: 0.01rem solid white;
        background-color: rgba(255,255,255,.05);
        color: white;
    }
    .search #search_from > input::-webkit-input-placeholder {
        color: white;
    }
    .search > .search-btn {
        width: 0.5rem;
        position: relative;
    }
    .search > .search-btn > img {
        width: 0.25rem;
        position: absolute;
        top: 50%;
        left: 50%;
        transform: translate(-50%,-50%);
    }
    .history {
        height: 0.9rem;
        overflow: auto;
        background-color: rgba(255,255,255,.05);
        transition-duration: 0.5s;
    }
    .historys {
        margin-top: 0.8rem;
        overflow: hidden;
    }
    .history .history-item {
        display: flex;
        height: 0.4rem;
        border-bottom: 0.01rem dashed #cccccc;
        align-items: center;
        justify-content: space-evenly;
    }
    .history .history-item > .history-time {
        font-size: 0.14rem;
    }
    .history .history-item > .history-city {
        font-size: 0.18rem;
    }
    .history .la {
        height: 0.3rem;
        display: flex;
        position: fixed;
        top: 0.45rem;
        width: 90%;
        background-color: rgba(255,255,255,.0);
        justify-content: space-between;
        font-size: 0.16rem;
        border-bottom: 0.01rem solid white;
        margin: 0.1rem 0.2rem;
        font-family: 幼圆;
        line-height: 0.3rem;
    }
    .history .la > span {
        color: white;
    }
    .history .la > img {
        width: 0.2rem;
        height: 0.2rem;
        padding: 0.03rem;
        border: 0.01rem solid #cccccc;
        border-radius: 0.05rem;
    }
    .clearbtn {
        height: 0.3rem;
        text-align: center;
        text-decoration: underline;
        font-size: 0.2rem;
        margin-top: 0.1rem;
        line-height: 0.3rem;
    }
    .information {
        /*background-color: gold;*/
    }
    .now {
        padding-top: 0.2rem;
        display: flex;
        flex-direction: column;
    }
    .now .city {
       font-size: 0.4rem;
        text-align: center;
    }
    .now .situation {
        padding-top: 0.2rem;
        display: flex;
        justify-content: space-evenly;
        font-size: 0.15rem;
        align-items: center;
    }
    .now .situation > img {
        width: 1rem;
        height: 1rem;
        vertical-align: bottom;
    }
    .now .temp {
        display: flex;
        flex-direction: column;
        align-items: center;
    }
    .now .temp > h3 {
        font-size: 0.2rem;
        margin-top: 0.1rem;
    }
    .forecast {
        background-color: rgba(0,0,0,.3);
        margin: 0 0.2rem;
        border-radius: 0.1rem;
    }
    .forecast-item {
        height: 0.3rem;
        display: flex;
        justify-content: space-between;
        margin: 0.1rem 0.2rem 0;
        padding-top: 0.1rem;
    }
    .forecast-item:last-of-type {
        padding-bottom: 0.1rem;
    }
    .forecast-item .forecast-situation > img {
        width: 0.2rem;
        height: 0.2rem;
    }
    .forecast-item .forecast-situation {
        font-size: 0.16rem;
    }
    .forecast-temp {
        font-size: 0.18rem;
    }
    .lifestyle {
        display: none;
        margin: 0 0.2rem;
        background-color: rgba(0,0,0,.3);
        border-radius: 0.1rem;
    }
    .lifestyle > h2 {
        text-align: center;
        margin-top: 0.2rem;
        font-size: 0.2rem;
        padding-top: 0.15rem;
        font-family: 幼圆;
    }
    .lifestyle .lifestyle-box {
        display: flex;
        flex-wrap: wrap;
        justify-content: space-between;
    }
    .lifestyle .lifestyle-box .lifestyle-item {
        display: flex;
        flex-direction: column;
        width: 0.7rem;
        height: 0.4rem;
        font-size: 0.14rem;
        text-align: center;
        padding-top: 0.1rem;
        padding-bottom: 0.05rem;
    
    }
    .lifestyle .lifestyle-box .lifestyle-item > i {
        font-size: 0.2rem;
    }
    .lifestyle .lifestyle-box .lifestyle-item > span {
        white-space: nowrap;
        text-overflow:ellipsis;
        overflow:hidden;
    }
    .lifestyle-tc {
        height: 100vh;
        position: fixed;
        top: 0;
        left: 0;
        background-color: gold;
        font-family: 幼圆;
        line-height: 0.4rem;
    
    }
    .lifestyle-tc .fanghui {
        width: 0.3rem;
        height: 0.3rem;
        position: absolute;
        left: 0.2rem;
        top: 0.1rem;
    }
    .lifestyle-tc .fanghui > img {
        width: 100%;
    }
    .lifestyle-tc > h2 {
        font-size: 0.3rem;
        width: 2.2rem;
        margin: 0.3rem auto 0;
        text-align: center;
    }
    .lifestyle-tc > span {
        width: 100%;
        font-size: 0.2rem;
        margin-top: 1.5rem;
        display: block;
        font-weight: 700;
        text-indent: 0.16rem;
    }
    .lifestyle-tc > p {
        text-indent: 0.32rem;
        font-size: 0.2rem;
    }
    

    JS代码

    let searchtext = document.querySelector('.search #search_from > input');
    let searchbtn = document.querySelector('.search-btn');
    let information = document.querySelector('.information'); //当前天气div
    let forecast = document.querySelector(".forecast"); //获取天气预报 div
    let lifestyle = document.querySelector('.lifestyle');
        if (localStorage.tq == undefined) {   /*如果默认没搜索过 就自动搜索普宁*/
        var tqList = [];
        let defauleCity = "普宁";
        autorend(defauleCity);
        } else {  /*如果有搜索记录,就自动搜索最后一次机城市*/
        var tqList = JSON.parse(localStorage.tq);
        let endcityName = tqList[tqList.length - 1].cityName;
        autorend(endcityName);
    }
    
        /* 自动渲染方法*/
        function autorend (cityName) {
        let nowurl = "https://free-api.heweather.net/s6/weather/now?location="+cityName+"&key=26be256aca2c43a7bb7f9a72e0f99a6b";
        let dailyurl = "https://free-api.heweather.net/s6/weather/forecast?location="+cityName+"&key=26be256aca2c43a7bb7f9a72e0f99a6b";
        let lifestyleurl = "https://free-api.heweather.net/s6/weather/lifestyle?location="+cityName+"&key=26be256aca2c43a7bb7f9a72e0f99a6b";
            console.log("执行自动渲染")
        rendweather(nowurl,cityName,dailyurl,lifestyleurl);
    }
    
        function getTime() {
            let date = new Date();
            let year = date.getFullYear();
            let month = date.getMonth() + 1;
            let day = date.getDate();
            let house = date.getHours();
            house = house < 10 ? '0' + house : house;
            let minutes = date.getMinutes();
            minutes = minutes < 10 ? '0' + minutes : minutes;
            let second = date.getMinutes();
            second = second < 10 ? '0' + second : second;
            let time = year + "年 - " +  month + "月 - " + day + "日 - " + house + ":" + minutes + ":" + second;
            return time;
        }
    
        /*搜索按钮事件*/
        searchbtn.addEventListener('click',function () {
        let time = getTime();
        let cityName = searchtext.value;
        /*如果输入框不为空才执行  不加这条件 会导致传入一个空的字符串 导致历史记录添加到一个空的*/
        if (cityName != "") {
            let List = {
                "cityName" : cityName,
                "time" : time
            }
            tqList.push(List);
            localStorage.tq = JSON.stringify(tqList);
            rendhistory(tqList);
            let nowurl = "https://free-api.heweather.net/s6/weather/now?location="+cityName+"&key=26be256aca2c43a7bb7f9a72e0f99a6b";
            let dailyurl = "https://free-api.heweather.net/s6/weather/forecast?location="+cityName+"&key=26be256aca2c43a7bb7f9a72e0f99a6b";
            let lifestyleurl = "https://free-api.heweather.net/s6/weather/lifestyle?location="+cityName+"&key=26be256aca2c43a7bb7f9a72e0f99a6b";
            rendweather(nowurl,cityName,dailyurl,lifestyleurl);  /*调用渲染方法*/
            searchtext.value = "";
        }
    });
    
        /*手机键盘搜索键事件*/
        document.getElementById('search_from').onsubmit = function () {
            searchbtn.click();
            document.activeElement.blur();
        }
    
        /*主页面渲染*/
        function rendweather (nowurl,cityName,dailyurl,lifestyleurl) {
            /*获取今日天气信息*/
            getAjax(nowurl,function (xhr) {
                let databoj = JSON.parse(xhr.response);
                let now = databoj.HeWeather6[0].now;
                if (now == undefined) {  /* 如果获取到的为now   说明用户输入的城市有误*/
                    if (tqList.length > 1) {//如果长度大于1 说明之前用户正确输入过城市
                        tqList.splice(tqList.length - 1 , 1 );  //执行删除最后一个元素  即输入错误的城市
                        rendhistory(tqList);  //  执行历史记录渲染
                        cityName = tqList[tqList.length - 1].cityName;   //将城市名赋值为数组最后一个元素 即最后一次正确搜索的城市
                    } else if (tqList.length == 1) {  /* 如果长度为1 说明现在为止用户没输入一个正确的城市*/
                        cityName = "普宁";  //将城市名赋值为 普宁
                        // tqList.splice(tqList.length - 1 , 1 );
                        tqList.pop();  //删除输入错误的文字
                        rendhistory(tqList);  //执行历史记录渲染
                    }
                    autorend(cityName);  //最后执行自动渲染
                } else {  //如果以上都没错误 说明用户输入的城市正确  正常执行代码
                    /* 渲染今日天气*/
                    information.innerHTML = `
                <div class="now">
                <span class="city">${cityName}</span>
                <div class="situation">
                    <img src="https://cdn.heweather.com/cond_icon/${now.cond_code}.png" alt="">      <!-- 天气图标 -->
                    <h1 class="text">${now.cond_txt}</h1> <!-- 天气状况 -->
                    <div class="temp">
                        <h3 class="tmp">温度:${now.tmp}℃</h3>        <!-- 温度 -->
                        <h3 class="fl">体感温度:${now.fl}℃</h3>         <!-- 体感温度 -->
                    </div>
                </div>
            `;
                    /*渲染背景图片*/
                    let nowcondtxt = now.cond_code;
                    switch(nowcondtxt) {
                        case "101":
                        case "102":
                        case "103":
                        case "104":
                            document.body.style.backgroundImage = "url('images/2.jpg')";
                            break;
                        case "100":
                        case "200":
                        case "201":
                        case "202":
                        case "203":
                        case "204":
                            document.body.style.backgroundImage = "url('images/1.jpg')";
                            break;
                        case "205":
                        case "206":
                        case "207":
                        case "208":
                        case "209":
                            document.body.style.backgroundImage = "url('images/7.jpg')";
                            break;
                        case "210":
                        case "211":
                        case "212":
                        case "213":
                            document.body.style.backgroundImage = "url('images/8.jpg')";
                            break;
                        case "300":
                        case "301":
                        case "302":
                        case "303":
                        case "304":
                        case "305":
                        case "306":
                        case "307":
                        case "308":
                        case "309":
                        case "310":
                        case "311":
                        case "312":
                        case "313":
                        case "314":
                        case "315":
                        case "316":
                        case "317":
                        case "318":
                        case "399":
                            document.body.style.backgroundImage = "url('images/3.jpg')";
                            break;
                        case "400":
                        case "401":
                        case "402":
                        case "403":
                        case "404":
                        case "405":
                        case "406":
                        case "407":
                        case "408":
                            document.body.style.backgroundImage = "url('images/4.jpg')";
                            break;
                        case "500":
                        case "501":
                        case "502":
                        case "503":
                        case "504":
                        case "505":
                        case "506":
                        case "507":
                        case "508":
                            document.body.style.backgroundImage = "url('images/5.jpg')";
                            break;
                        case "509":
                        case "510":
                        case "511":
                        case "512":
                        case "513":
                        case "514":
                        case "515":
                            document.body.style.backgroundImage = "url('images/6.jpg')";
                            break;
                        default:
                            document.body.style.backgroundImage = "url('images/9.jpg')";
                    }
    
                    /*获取天气预告信息*/
                    getAjax(dailyurl,function (xhr) {
                        forecast.innerHTML = "";  /*清除之前的渲染*/
                        let databoj = JSON.parse(xhr.response);
                        let daily = databoj.HeWeather6[0].daily_forecast;
                        daily.forEach(function (item,index) {
                            /*如果当天天气早上和晚上一样就输出一个  如果不一样 就早上转晚上(天气类型)*/
                            var txt =  item.cond_txt_d == item.cond_txt_n ? item.cond_txt_d : item.cond_txt_d + "转" + item.cond_txt_n;
                            let date = '今天';  /*默认今天*/
                            if (index == 1) {  /* 第二个赋值为明天*/
                                date = "明天";
                            } else if (index == 2) {  /* 第三个赋值为后天*/
                                date = "后天";
                            }
                            /*渲染天气预报*/
                            forecast.innerHTML += `
                        <div class="nowday forecast-item">
                                 <div class="forecast-situation">
                                 <img src="https://cdn.heweather.com/cond_icon/${item.cond_code_d}.png" alt="">
                                 ${date} * <span class="txt">${txt}</span>
                         </div>
                             <div class="forecast-temp">
                                    <span class="max">${item.tmp_max}°/</span>
                                    <span class="min">${item.tmp_min}°</span>
                             </div>
                </div>`;
                        })
                    });
    
                    lifestyle.style.display = 'block'; /*显示生活指数模板*/
                    /*获取生活指数*/
                    getAjax(lifestyleurl,function (xhr) {
                        let databoj = JSON.parse(xhr.response);
                        let lifestyle = databoj.HeWeather6[0].lifestyle;
                        lifestyleclick(lifestyle);  /*调用生活指数渲染方法*/
                    });
                }
            });
        }
    
        /*生活指数渲染方法*/
        let lifestyleitem = document.querySelectorAll('.lifestyle-item');
        function lifestyleclick (lifestyle) {
            for (let j = 0; j < lifestyleitem.length; j ++) {
                lifestyleitem[j].onclick = function () {
                    let index = lifestyleitem[j].dataset.indexs;
                    let li = lifestyle[index];
                    let lifestyletc = document.querySelector('.lifestyle-tc');
                    lifestyletc.innerHTML = `<div class="fanghui">
                             <img src="images/fanghui.png" alt="">
                                                </div>
                             <h2>${lifestyleitem[j].children[1].childNodes[0].data}</h2>
                             <span>${li.brf}</span>
                             <p>"${li.txt}"</p>`;
                    lifestyletc.style.display = 'block';
                    /*关闭按钮*/
                    let fanghuibtn = document.querySelector('.fanghui');
                    console.log(fanghuibtn);
                    fanghuibtn.onclick = function () {
                        lifestyletc.style.display = 'none';
                    }
                }
            }
        }
    
    
        //历史记录事件
        let historys = document.querySelector('.historys');
        function rendhistory(tqList) {
            historys.innerHTML = "";  /*每次执行历史记录渲染都清除之前的记录 防止出现重复*/
            tqList.forEach(function (item,index) {
                /*将历史记录写入*/
                historys.innerHTML += `
                <div class="history-item" data-indexs="${index}">
                    <span class="history-time">${item.time}</span>
                    <span class="history-city">${item.cityName}</span>
                 </div>
                `;
            })
    
            /*获取历史记录div 添加点击事件
            * 点击后跳转点击的城市
            * */
            let historyitem = document.querySelectorAll('.history-item');
            for (let j = 0; j < historyitem.length; j ++) {
                historyitem[j].onclick = function() {
                    let index = historyitem[j].dataset.indexs;
                    let thecityName = tqList[index].cityName;
                    let time = getTime();
                    let List = {
                        "cityName" : thecityName,
                        "time" : time
                    }
                    tqList.push(List);
                    localStorage.tq = JSON.stringify(tqList);
                    rendhistory(tqList);
                    autorend(thecityName);
                }
            }
        }
        rendhistory(tqList);
        xiala();
        //下拉菜单事件
        function xiala () {
            let historybtn = document.querySelector('.la > img');
            let historyDiv = document.querySelector('.history');
            let clearhistory = document.querySelector('.clearbtn');
            let flag = true;
            historybtn.addEventListener('click',function () {
                if (flag) {
                    flag = false;
                    historybtn.style.backgroundColor = "rgba(0,0,0,.3)";
                    let height = (tqList.length * 0.4) + 1.7;
                    historyDiv.style.height = height + 'rem';
                } else {
                    flag = true;
                    historybtn.style.backgroundColor = "rgba(0,0,0,.0)";
                    historyDiv.style.height = '0.9rem';
                }
            });
            clearhistory.addEventListener('click',function () { /*清除历史记录事件*/
                localStorage.removeItem('tq'); /*删除本地存储*/
                tqList = []; /*将数组清空*/
                rendhistory(tqList);  /*渲染历史记录*/
                historybtn.click();  /*执行下拉按钮点击*/
            });
            searchtext.addEventListener('click',function () { //点击输入框 如果下拉菜单打开 就关闭
                if (!flag) {
                    historybtn.click();
                }
            });
        }
    
    
    展开全文
  • js天气预报 js天气预报接口

    热门讨论 2011-05-17 08:52:22
    js版得,可能显示的比较慢,显示不出来刷新下,经本人测试,可以显示出来,先去QQ查看ip,然后把ip转换为城市,最后由城市代码去查看天气
  • js天气预报 html页面

    热门讨论 2011-03-07 15:53:20
    js天气预报 天气预报代码 页面好的js天气预报js天气预报js天气预报js天气预报
  • JS天气预报项目 主要完成功能: 页面展示 城市以及对应温度时实获取 当前日期以及最高低温 生活播报 今日各个时段的温度和图标等等 1.代城市切换完成图展示 2.时实温度完成图 总体完成图 代码部分: (总体结构...

    JS天气预报项目

    主要完成功能:

    1. 页面展示
    2. 城市以及对应温度时实获取
    3. 当前日期以及最高低温
    4. 生活播报
    5. 今日各个时段的温度和图标等等

    1.代城市切换完成图展示在这里插入图片描述在这里插入图片描述
    在这里插入图片描述
    2.时实温度完成图在这里插入图片描述
    总体完成图
    在这里插入图片描述

    代码部分:
    (总体结构代码)
    在这里插入图片描述
    js的主要部分,其他引入都类似~
    1.先获取天气的API
    2获取data数据
    3引入到相应标签最后重新渲染innerHTML就可以了~

    
    fetch(`https://free-api.heweather.net/s6/weather/forecast${location.search}&key=4e0e859d0cf84681b909217c23d9fb6c`,{
        method:"get",
        mode:'cors'
    })
    .then(r=>r.json())
    .then(data=>{
        //console.log(data)
    
         let mstring=""
    
         data.HeWeather6.forEach(value=>{
             mstring+=
             `
             <span>${value.daily_forecast[0].tmp_min}&nbsp&nbsp${value.daily_forecast[0].tmp_max}</span>
    
             `
             
         })
         $('.span').innerHTML=mstring
    
       })
    
    

    新建一个get.js

    function $(e){
       return document.querySelector(e)
    }
    
    

    由于引入icon图标,html代码看起来比较多就不复制了~各时段温度页面可以再美化下,js中的API获取各个数据大概就是这样的模板

    展开全文
  • 仿照webQQ的天气样式做的一个天气预报,使用中国天气的数据源
  • 博客参考https://blog.csdn.net/hongfei568718926/article/details/109117723
  • js天气预报

    热门讨论 2012-12-25 14:54:58
    这几天突发奇想,突然想自己写一个js跨域访问天气的接口然后实现天气预报功能的小例子 但是jquery跨域访问的时候出现了点问题 上csdn上晃悠了一大圈发现大多是答非所问 不少东西花积分下载之后 例子里面根本就只提供...
  • 个人原创,界面美观,几乎把webservice上的所有数据显示在页面上,使用JQuery和Javascript做的,效果不错的,直接打开index.html就能看到效果(最好使用ie9以上的)
  • php实现天气预报

    热门讨论 2011-12-23 19:36:12
    代码+部署使用说明
  • 准备的文件如下: template.js文件下载 链接:https://pan.baidu.com/s/1FOcJehGQCBfdi5fxIJjVnQ 提取码:62in jquery-1.4.2.min.js文件 ...提取码:6gvc 天气api接口 网站:https://www.kancloud.c...
  • 本文实例为大家分享了Android九宫格图片展示的具体代码,供大家...天气</title> [removed][removed] [removed] var u1=https://free-api.heweather.com/v5/weather?city=; var u2; var u3=&key=545d63e185
  • 代码 在前端页面插入下面代码即可 里面的参数就自己改去吧 <iframe width="415" scrolling="no" height="50" frameborder="0" allowtransparency="true" src=...id=12&icon=1&num=3&site=12">......
  • 异步Ajax请求查看天气预报小案例 需要一个天气预报的后台接口:http://wthrcdn.etouch.cn/weather_mini?city=XX 通过Ajax访问后台 获取后台数据 后台JSON数据格式的解析读取操作 动态添加多个嵌套样式标签展示到...
  • 主要介绍了用python自制微信机器人,定时发送天气预报,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
  • 基于Vue开发的迷你实时天气预报组件 项目展示 基于Vue框架开发的一款迷你天气预报展示的小组件,目前只支持中国大陆的天气预报,原因在更新公告中有,有问题请提 :package: 安装 2021.04.24 因为刚上传到npm仓库没...
  • <div class="forecast"> div> <script src="http://pv.sohu.com/cityjson?ie=utf-8">script> <script src="js/weather.js">script> body> html> weather.css 整个板块的样式 * { padding: 0; margin: 0; } /* 今日...
  • 接下来是准备工作,可以搜索高德地图开放平台-Web服务API-天气查询。 天气查询是一个简单的HTTP接口,根据用户输入的adcode,查询目标区域当前/未来的天气情况。 使用API前您需先申请Key,若无高德地图API账号需要先...
  • 先上代码了 <html lang="en"> <head> <meta charset="UTF-8"> , initial-scale=1.0"> <meta http-equiv="X-UA-Compatible" content="ie=edge"> <title>H5 | 和风天气title> ...<script type="text/javascript" src=...
  • JS天气预报

    2016-05-10 23:38:35
    简易的使用 网络请求 数据解析,实现天气预报
  • http: php weather sina com cn js php " + $ param { city : $ "#position" val 城市 day : 0 password : "DJOYnieT8234jlsK" } function json { $ "#weatherinfo" ...
  • DOM及AJAX实现天气预报查询 <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> ...

空空如也

空空如也

1 2 3 4 5 ... 20
收藏数 4,562
精华内容 1,824
关键字:

js实现天气预报