首頁 >web前端 >H5教程 >如何透過html5實現搖一搖的功能

如何透過html5實現搖一搖的功能

jacklove
jacklove原創
2018-06-09 10:04:082671瀏覽

原則:使用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 aallow roscope to 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(&#39;mybody&#39;).className = &#39;doing&#39;;
        document.getElementById(&#39;txt&#39;).innerHTML = &#39;执行了摇一摇&#39;;
        setTimeout(function(){
            doing=0; 
            document.getElementById(&#39;mybody&#39;).className=&#39;normal&#39;;
            document.getElementById(&#39;txt&#39;).innerHTML = &#39;请执行摇一摇&#39;;
        },3000);
    }
    window.addEventListener("devicemotion", handleMotionEvent, true); </script></html>

本文介紹了透過html5實現搖一搖的功能,更多相關內容請關注php中文網。

相關推薦:

如何透過MySql查看與修改auto_increment的方法

如何透過php產生網頁桌面的快捷方式

利用js遍歷取得表格內資料的方法


以上是如何透過html5實現搖一搖的功能的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn