美文网首页Web前端之路让前端飞技术干货
HTML5简明教程(七)其他新技术

HTML5简明教程(七)其他新技术

作者: 娜姐聊前端 | 来源:发表于2017-05-11 23:33 被阅读150次

最后一部分介绍HTML5其他新技术。

1. 地理位置

HTML5地理定位功能由navigator.geolocation对象提供,API方法有三个:

  • getCurrentPosition: 获取当前位置信息,包含经纬度,海拔,精度。
navigator.geolocation.getCurrentPosition(successCallback, [errorCallback] , [positionOptions]);
  • watchPosition:定期轮询设备位置信息,函数入参和getCurrentPosition相同。
var watchID = navigator.geolocation.watchPosition(successCallback, [errorCallback] , [positionOptions]);
  • clearWatch:配合watchPosition()使用,停止轮询
clearWatch(watchID);

浏览器在加载位置信息时,会开启询问窗口,需要用户确定后才允许网站访问该数据。

confrim dialog.png

查找坐标的方法是异步的,不会立刻返回数据,所以需要回调函数来处理成功或失败消息。下面是一个简单的例子,点击“location”按钮访问位置信息:

<body>
<button onclick="getPosition()">Location!</button>
<div id="info"></div>
<script>
    var infoElt = document.getElementById("info");
    function getPosition() {
        if (navigator.geolocation) {
            navigator.geolocation.getCurrentPosition(geolocationSuccess,
                geolocationFailure,
                {
                    enableHighAccuracy: true, // 用高精度GPS位置检测
                    timeout: 100000, // 等待位置数据返回的最大时间
                    maximunAge: 300000 // 缓存位置数据时间
                })
        }
        else {
            infoElt.textContent = "Do not support navigator.geolocation!";
        }
    }

    // 成功时的回调函数
    function geolocationSuccess(position) {
        infoElt.textContent = "Location: " + position.coords.latitude + ";" + position.coords.longitude;
    }

    // 失败时的回调函数
    function geolocationFailure(error) {
        infoElt.textContent = "Error: code is " + error.code + "; message is " + error.message;
    }
</script>
</body>
小贴士

navigator是JavaScript中一个比较特殊的对象,它的属性包含当前浏览器的信息。
比如,最常用的navigator.userAgent,返回浏览器的版本号,操作系统等细节。
这个属性常用于检测移动设备操作系统,IOS或者Android。

2. history对象

单页面应用中使用的路由系统,常用的实现方式是监听锚地变化,即Hashbang URL。另一只实现方式就是利用history对象管理会话历史,在URL变化的情况下不刷新页面。

history对象提供3个方法:

  • pushState(): 添加新的历史条目
  • replaceState(): 用新条目替代已有的历史条目
  • popstate事件: 每当激活的历史记录发生变化时,该事件被触发(激活的历史记录为用pushState创建的历史条目)

例如,调用history.pushState(pageData, pageData.title, pageURL);方法添加一条新的历史几句,页面URL发生变化,这时会触发popstate事件,在事件回调中,可以做UI方面的更新操作,同时,页面不会reload。

window.addEventListener('popstate', function(event) {
  updateContent();
});

3. 拖拽

HTML5提供拖拽的API,可以在需要拖拽/目标的元素上监听这些事件,从而操作DOM元素。

相关事件有:

  • ondragstart:当拖拽元素开始被拖拽的时候触发的事件(作用在被拖曳元素上)
  • ondragenter:当拖曳元素进入目标元素的时候触发的事件(作用在目标元素上)
  • ondragover:拖拽元素在目标元素上移动的时候触发的事件(作用在目标元素上)
  • ondrop 事件:被拖拽的元素在目标元素上同时鼠标放开触发的事件(作用在目标元素上)
  • ondragend 事件:当拖拽完成后触发的事件(作用在被拖曳元素上)

可以参考https://github.com/etianqq/html5-dnd-demo ,这个demo实现了在列表上拖拽列表项从而实现重新排序的功能。

4. 跨域通信postMessage

window.postMessage()可以实现跨域通信,当调用此方法时,会向目标窗口发送一个MessageEvent消息,目标窗口通过监听事件接受消息。

主要用于跨域iframe直接通信。

语法为:

otherWindow.postMessage(message, targetOrigin, [transfer]);

* otherWindow:其他窗口的一个引用,比如iframe的contentWindow属性
* message:消息
* targetOrigin:目标地址
* transfer(可选):和message一起传递的对象

在父窗口http://my.example.com中定义发送和接受消息:

<body>
<input type="button" value="get data from child frame" onclick="getData()"/>
<div id="result"></div>

<iframe src="http://child.example.com/api.html" frameborder="0" id="child-frame" style="display: none">
</iframe>

<script>
    function getData(){
        frames[0].postMessage('http://child.example.com/some-data', 'http://child.example.com');
    }

    window.addEventListener('message', function(event){
        if (event.origin !== 'http://child.example.com'){
            return;
        }

        document.getElementById('result').innerHTML = event.data;
    }, false);
</script>
</body>

在子窗口http://child.example.com中定义发送和接受消息:

<script>
    window.addEventListener('message', function(event){
        if (event.origin !== 'http://my.example.com'){
            return;
        }
        var xhr = new XMLHttpRequest();
        xhr.onreadystatechange = function(){
            if (xhr.readyState ==4 && xhr.status ==200){
                event.source.postMessage(xhr.responseText, 'http://my.example.com');
            }
        };

        var url = event.data;
        xhr.open(url, 'GET');
        xhr.send(null);
    }, false);
</script>

小结

当然,HTML5的功能还不止于系列文章中所提到的,在《HTML5简明教程》中,只是把最常用的也是比较有特色的新特性介绍给大家,如有兴趣,可以去探索更多HTML5的优秀功能。

微信公众号:

相关文章

网友评论

    本文标题:HTML5简明教程(七)其他新技术

    本文链接:https://www.haomeiwen.com/subject/xojstxtx.html