• html5实现摇一摇功能


    原理:使用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; 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">
        <div id="txt" class="txt center">请执行摇一摇</div>
     </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>


  • 相关阅读:
    JavaScript内置对象
    微信小程序:实现可拖动悬浮图标(包括按钮角标的实现)
    项目1——博客系统
    在HTML中使用css3实现雪人动画效果
    Ajax请求后台发送String类型总是进入Error function解决办法总结
    原生js实现图片懒加载
    【Electron Playground 系列】自定义协议篇
    大规格文件的上传优化
    如何优雅的在react-hook中进行网络请求
    noip2008 双栈排序
  • 原文地址:https://www.cnblogs.com/hehe520/p/6147461.html
Copyright © 2020-2023  润新知