• 技术文章 >web前端 >H5教程

    如何通过html5实现摇一摇的功能

    jacklovejacklove2018-06-09 10:04:08原创1297
    原理:使用DeviceMotion实现,关于DeviceMotion介绍可以查看
    https://developer.mozilla.org/en-US/docs/Web/Reference/Events/devicemotion

    通过DeviceMotionEvent,可以获得accelerationIncludingGravity的x,y,z属性,根据x,y,z属性的变化来判断设备是否有摇一摇的事件发生。

    accelerationIncludeingGravity说明:
    The acceleration of the device. This value includes the effect of gravity, and may be the only value available on devices that don’t have a gyroscope to allow them to properly remove gravity from the data.

    代码如下:

    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"><html>
     <head>
      <meta http-equiv="content-type" content="text/html;charset=utf-8">    
      <title> html5使用DeviceMotionEvent实现摇一摇 </title>
      <style type="text/css">
      .center{position:absolute; width:640px; height:480px; left:50%; top:50%; margin-left:-320px; margin-top:-240px; line-height:480px; text-align:center; font-size:100px; }
      .normal{background:#000000;}
      .normal .txt{color:#FFFFFF;}
      .doing{background:#FF0000;}
      .doing .txt{color:#FFFF00;}
      </style>
     </head>
     <body id="mybody" class="normal">
        <p id="txt" class="txt center">请执行摇一摇</p>
     </body>
     <script type="text/javascript">
        var doing = 0;  // 判断是否在动画显示中
        var speed = 23; // 定义摇动的速度数值
        var lastx = 0;    var lasty = 0;    var lastz = 0;    function handleMotionEvent(event) {
            var x = event.accelerationIncludingGravity.x;        var y = event.accelerationIncludingGravity.y;        var z = event.accelerationIncludingGravity.z;        if(doing==0){            if(Math.abs(x-lastx)>speed || Math.abs(y-lasty)>speed){
                    doing = 1;
                    show();
                }
            }
            lastx = x;
            lasty = y;
            lastz = z;
        }    function show(){
            document.getElementById('mybody').className = 'doing';
            document.getElementById('txt').innerHTML = '执行了摇一摇';
            setTimeout(function(){
                doing=0; 
                document.getElementById('mybody').className='normal';
                document.getElementById('txt').innerHTML = '请执行摇一摇';
            },3000);
        }
        window.addEventListener("devicemotion", handleMotionEvent, true); </script></html>

    本文介绍了通过html5实现摇一摇的功能,更多相关内容请关注php中文网。

    相关推荐:

    如何通过MySql查看与修改auto_increment的方法

    如何通过php生成网页桌面的快捷方式

    利用js遍历获取表格内数据的方法

    以上就是如何通过html5实现摇一摇的功能的详细内容,更多请关注php中文网其它相关文章!

    声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
    专题推荐:html5 device
    上一篇:html5触摸事件判断滑动方向的实现 下一篇:关于HTML5 localStorage and sessionStorage 之间的区别
    PHP编程就业班

    相关文章推荐

    • html5离线存储有哪些• 深入解析asp.net中mvc4自定义404页面(分享)• h5新增标签audio与video的使用• 避免常见的六种HTML5错误用法 (5-6)• 你值得了解的HTTP缓存机制(代码详解)

    全部评论我要评论

  • 取消发布评论发送
  • 1/1

    PHP中文网