码迷,mamicode.com
首页 > Web开发 > 详细

HTML5--新增常用接口/网络状态监听/全屏/fileReader/定位/存储一(11)

时间:2018-04-30 15:30:23      阅读:276      评论:0      收藏:0      [点我收藏+]

标签:应用程序   strong   第三部分   block   二进制   开放平台   getc   type   地理信息   

这节主要学习HTML5中新增常用的API,包括网络状态监听、全屏、fileReader文件、定位、存储.....,很多接口在浏览器端存在兼容问题,需要进行兼容处理。

第一部分--网络状态监听接口

    作用:判断当前的网络连接状态,根据网络状态进行相应的操作。

  方法:

    ononline:当网络连通时触发此事件

    onoffline:当网络断开时触发此事件

<body>
    <script>
        window.addEventListener("online", function () {
            alert("网络连通了");
        });
        window.addEventListener("offline", function () {
            alert("网络断开了");
        });
    </script>
</body>

第二部分--全屏接口

    作用:对元素/文档的全屏缩放操作的控制

  方法:

    requestFullScreen开启全屏显示,不同的浏览器需要添加不同的前缀
    cancelFullScreen退出全屏显示,不同浏览器需要添加不同的前缀,只能用document调用(是整个文档退出,而非某个元素退出,所以需要用document调用)
    fullScreenElement:判断是否处于全屏状态,也只能用document调用
<body>
    <div>
        <img src="../images/l1.jpg" alt="">
        <input type="button" id="full" value="全屏">
        <input type="button" id="cancelFull" value="退出全屏">
        <input type="button" id="isFull" value="是否全屏">
    </div>
    <script>
        window.onload=function(){
            var div=document.querySelector("div");
            // /!*全屏操作*!/
            document.querySelector("#full").onclick=function(){
                // /!*使用能力测试添加不同浏览器下的前缀*!/
                if(div.requestFullScreen){
                    div.requestFullScreen();
                }
                else if(div.webkitRequestFullScreen){
                    div.webkitRequestFullScreen();
                }
                else if(div.mozRequestFullScreen){
                    div.mozRequestFullScreen();
                }
                else if(div.msRequestFullScreen){
                    div.msRequestFullScreen();
                }
            }

            // /!*退出全屏*!/
            document.querySelector("#cancelFull").onclick=function(){
                if(document.cancelFullScreen){
                    document.cancelFullScreen();
                }
                else if(document.webkitCancelFullScreen){
                    document.webkitCancelFullScreen();
                }
                else if(document.mozCancelFullScreen){
                    document.mozCancelFullScreen();
                }
                else if(document.msCancelFullScreen){
                    document.msCancelFullScreen();
                }
            }

            // /!*判断是否是全屏状态*!/
            document.querySelector("#isFull").onclick=function(){
                // /!*两个细节:使用document判断  能力测试*!/
                if(document.fullscreenElement || document.webkitFullscreenElement || document.mozFullScreenElement || document.msFullscreenElement){
                    alert(true);
                }
                else{
                    alert(false);
                }
            }
        }
    </script>
</body>

第三部分--fileReader文件接口

  作用:读取文件内容,并返回读取的内容(字符串)

  方法

    readAsText():读取文本文件内容,返回字符串,默认编码是UTF-8.

    readAsBinaryString():读取任意类型文件内容,返回二进制字符串。此方法不是用来读文件给用户看,而是存储文件。例如:前端读取文件内容,获取二进制数据,传递给后台,后台接收了数据并将数据存储。

    readAsDataURL():读取文件获得以data开头的字符串,字符串的本质就是DataURL,

DataURL是将资源转换为base64编码的字符串形式,并且将这些内容直接存储在url中。

    abort():中止读取。

  举例:即时预览

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        div{
            height: 20px;
            width: 0%;
            background-color:red;
        }
    </style>
</head>
<body>
<form action="">
    文件: <input type="file" name="myFile" id="myFile"> <br>
    <div></div>
    <input type="submit">
</form>
<img src="" alt="">
<script>
   var div=document.querySelector("div");
    function getFileContent(){
       /!*1.创建文件读取对象*!/
        var reader=new FileReader();
       /*  /!*2.读取文件,获取DataURL
        * 2.1.说明没有任何的返回值:void:但是读取完文件之后,它会将读取的结果存储在文件读取对象的result中
        * 2.2.需要传递一个参数 binary large object:文件(图片或者其它可以嵌入到文档的类型)
        * 2.3:文件存储在file表单元素的files属性中,它是一个数组*!/ */
        var file=document.querySelector("#myFile").files;
        reader.readAsDataURL(file[0]);
        /!*获取数据*!/
        /* /!*FileReader提供一个完整的事件模型,用来捕获读取文件时的状态
        * onabort:读取文件中断片时触发
        * onerror:读取错误时触发
        * onload:文件读取成功完成时触发
        * onloadend:读取完成时触发,无论成功还是失败
        * onloadstart:开始读取时触发
        * onprogress:读取文件过程中持续触发*!/ */
        reader.onload=function(){
            /!*展示*!/
            document.querySelector("img").src=reader.result;
        }

        reader.onprogress = function (e) {
            //var percent= e.loaded/ e.total*100+"%";
            console.log(e);
            div.style.width = percent;
        };
    }
</script>
</body>

第四部分--地理定位接口

  作用:获取用户的地理位置信息,可以基于用户的位置开发基于位置服务的应用。

  注意:浏览器自动选择定位方式,我们无法设置浏览器的定位方式浏览器默认不允许获取当前用户的位置信息,可以手动设置在设置--高级设置--内容设置--位置(chrome)。

    对象1:Geolocation使用navigator.geolocation获取

        方法1:getCurrentPosition(success, [error], option):获取当前用的地理信息。

        参数:

          success:获取地理信息成功后执行的回调。

          error:获取地理信息失败后执行的回调。

          option设置获取当前地理信息的方式

            选项:enableHighAccuracy:true/false:是否使用高精度

                  timeout:设置超时时间,单位ms

                                                      maximumAge:可以设置浏览器重新获取地理信息的时间间隔单位是ms

        方法2:watchPosition(success, [error], option):循环监听用户的地理信息

        方法3:clearWatch():清除用户信息监听实例。

 

<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        .de{
            width: 300px;
            height: 300px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
<div id="demo" class="de"></div>
<script>
    var x=document.getElementById("demo");
    function getLocation()
    {
        if (navigator.geolocation)
        {
            /* /!*option:可以设置获取数据的方式
            * enableHighAccuracy:true/false:是否使用高精度
            * timeout:设置超时时间,单位ms
            * maximumAge:可以设置浏览器重新获取地理信息的时间间隔,单位是ms*!/ */
            navigator.geolocation.getCurrentPosition(showPosition,showError,{
                enableHighAccuracy:true,    //使用高精度
                timeout:3000    //超时时间设置3s
            });
        }
        else{
            x.innerHTML="Geolocation is not supported by this browser.";
        }
    }
    /* 成功获取定位之后的回调
    如果获取地理信息成功,会将获取到的地理信息传递给成功之后的回调 */
    // position.coords.latitude 纬度
    // position.coords.longitude 经度
    // position.coords.accuracy 精度
    // position.coords.altitude 海拔高度
    function showPosition(position)
    {
        x.innerHTML="Latitude: " + position.coords.latitude +
                "<br />Longitude: " + position.coords.longitude;
    }
    // 获取定位失败之后的回调
    function showError(error)
    {
        switch(error.code)
        {
            case error.PERMISSION_DENIED:
                x.innerHTML="User denied the request for Geolocation."
                break;
            case error.POSITION_UNAVAILABLE:
                x.innerHTML="Location information is unavailable."
                break;
            case error.TIMEOUT:
                x.innerHTML="The request to get user location timed out."
                break;
            case error.UNKNOWN_ERROR:
                x.innerHTML="An unknown error occurred."
                break;
        }
    }
    getLocation();
</script>

 

  第三方地图接口使用:

  在需要地图功能时,我们考虑使用第三方平台(百度地图或其他的第三方接口)

  步骤:打开百度地图首页--->地图开放平台(底部)--->开发文档,然后可以着手尝试了。(要申请授权码)

  举例:普通地图和全景图

<head>
    <title>普通地图&全景图</title>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <!-- 此处的ak就是我们申请的秘钥 -->
    <script type="text/javascript" src="http://api.map.baidu.com/api?v=2.0&ak=DarF2LCCGzn6T16zgy8ZPkvYYE5CT6fu"></script>
    <style type="text/css">
        body, html{width: 100%;height: 100%;overflow: hidden;margin:0;font-family:"微软雅黑";}
        #panorama {height: 50%;overflow: hidden;}
        #normal_map {height:50%;overflow: hidden;}
    </style>
</head>
<body>
<div id="panorama"></div>
<div id="normal_map"></div>
<script type="text/javascript">
    //全景图展示
    var panorama = new BMap.Panorama(panorama);
    panorama.setPosition(new BMap.Point(116.404125,39.91405)); //根据经纬度坐标展示全景图
    panorama.setPov({heading: -40, pitch: 6});

    panorama.addEventListener(position_changed, function(e){ //全景图位置改变后,普通地图中心点也随之改变
        var pos = panorama.getPosition();
        map.setCenter(new BMap.Point(pos.lng, pos.lat));
        marker.setPosition(pos);
    });
    //普通地图展示
    var mapOption = {
        mapType: BMAP_NORMAL_MAP,
        maxZoom: 18,
        drawMargin:0,
        enableFulltimeSpotClick: true,
        enableHighResolution:true
    }
    var map = new BMap.Map("normal_map", mapOption);
    var testpoint = new BMap.Point(116.404125,39.91405);
    map.centerAndZoom(testpoint, 18);
    var marker=new BMap.Marker(testpoint);
    marker.enableDragging();
    map.addOverlay(marker);
    map.enableScrollWheelZoom(true);
    map.addControl(new BMap.MapTypeControl());
    marker.addEventListener(dragend,function(e){
        panorama.setPosition(e.point); //拖动marker后,全景图位置也随着改变
        panorama.setPov({heading: -40, pitch: 6});}
    );
</script>
</body>

第五部分--web存储API

  1.sessionStorage:存储数据到本地,存储的容量在5m左右。

<body>
    <input type="text" id="userName">
    <br>
    <input type="button" value="显示数据" id="showData">
    <input type="button" value="设置数据" id="setData">
    <input type="button" value="获取数据" id="getData">
    <input type="button" value="删除数据" id="removeData">
    <input type="button" value="清空数据" id="clearData">
    <script>
        document.querySelector("#setData").onclick=function(){
            // /!*获取用户名*!/
            var name=document.querySelector("#userName").value;
            // /!*存储数据*!/
            window.sessionStorage.setItem("userName",name);
        }
        // /!*获取数据*!/
        document.querySelector("#getData").onclick=function(){
            // /!*如果找不到对应名称的key,那么就会获取null*!/
            var name=window.sessionStorage.getItem("userName");
            alert(name);
        }
        // /!*删除数据*!/
        document.querySelector("#removeData").onclick=function(){
            // /!*在删除的时候如果key值错误,不会报错,但是也不会删除数据*!/
            window.sessionStorage.removeItem("userName1");
        }
    </script>
</body>

 

  2.localStorage:存储数据到本地,存储的容量在20m左右。

  特点:

    

  方法:和sessionStrage方法用法相同。

<body>
    <input type="text" id="userName">
    <br>
    <input type="button" value="设置数据" id="setData">
    <input type="button" value="获取数据" id="getData">
    <input type="button" value="删除数据" id="removeData">
    <script>
        document.querySelector("#setData").onclick = function () {
            var name = document.querySelector("#userName").value;
            /*使用localStorage存储数据*/
            window.localStorage.setItem("userName", name);
        }
        /*获取数据*/
        document.querySelector("#getData").onclick = function () {
            var name = window.localStorage.getItem("userName");
            alert(name);
        }
        /*清除数据*/
        document.querySelector("#removeData").onclick = function () {
            window.localStorage.removeItem("userName");
        }
    </script>
</body>

第六部分:应用缓存(mainfest)

  1.使用html5,通过创建cache manifest文件,可以轻松的创建web应用的离线版本。

  2.优势:

    i:可配置需要缓存的资源。

    ii:网络无连接应用仍可用。

    iii:本地读取缓存资源,不需要向服务器请求资源,缓解服务器负担,提升访问速度。

  3.使用

    i:文档<html>标签中需要包含manifest属性。

  举例:  

    首先创建HTML文件。

<!--manifest="应用程序缓存清单文件的路径  建议文件的扩展名是appcache,这个文件的本质就是一个文本文件"-->
<html lang="en" manifest="demo.appcache">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        img{
            width: 300px;
            display: block;
        }
    </style>
</head>
<body>
<img src="../images/l1.jpg" alt="">
<img src="../images/l2.jpg" alt="">
<img src="../images/l3.jpg" alt="">
<img src="../images/l4.jpg" alt="">
</body>
</html>

    创建manifest文件。

#表示注释。
CACHE MANIFEST #上面一句代码必须是当前文档的第一句 #需要缓存的文件清单列表 CACHE: #下面就是需要缓存的清单列表 ../images/l1.jpg ../images/l2.jpg # *:代表所有文件 #配置每一次都需要重新从服务器获取的文件清单列表 NETWORK: ../images/l3.jpg #配置如果文件无法获取则使用指定的文件进行替代 FALLBACK: ../images/l4.jpg ../images/banner_1.jpg # /:代表所有文件

 

HTML5--新增常用接口/网络状态监听/全屏/fileReader/定位/存储一(11)

标签:应用程序   strong   第三部分   block   二进制   开放平台   getc   type   地理信息   

原文地址:https://www.cnblogs.com/diweikang/p/8973625.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!