溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點(diǎn)擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

通過html5實(shí)現(xiàn)搖一搖的功能的方法

發(fā)布時(shí)間:2020-09-28 15:51:03 來源:億速云 閱讀:150 作者:小新 欄目:web開發(fā)

小編給大家分享一下通過html5實(shí)現(xiàn)搖一搖的功能的方法,希望大家閱讀完這篇文章后大所收獲,下面讓我們一起去探討吧!

原理:使用DeviceMotion實(shí)現(xiàn),關(guān)于DeviceMotion介紹可以查看
https://developer.mozilla.org/en-US/docs/Web/Reference/Events/devicemotion

通過DeviceMotionEvent,可以獲得accelerationIncludingGravity的x,y,z屬性,根據(jù)x,y,z屬性的變化來判斷設(shè)備是否有搖一搖的事件發(fā)生。

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實(shí)現(xiàn)搖一搖 </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">請執(zhí)行搖一搖</p>
 </body>
 <script type="text/javascript">
    var doing = 0;  // 判斷是否在動畫顯示中
    var speed = 23; // 定義搖動的速度數(shù)值
    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 = '執(zhí)行了搖一搖';
        setTimeout(function(){
            doing=0; 
            document.getElementById('mybody').className='normal';
            document.getElementById('txt').innerHTML = '請執(zhí)行搖一搖';
        },3000);
    }
    window.addEventListener("devicemotion", handleMotionEvent, true); </script></html>

看完了這篇文章,相信你對通過html5實(shí)現(xiàn)搖一搖的功能的方法有了一定的了解,想了解更多相關(guān)知識,歡迎關(guān)注億速云行業(yè)資訊頻道,感謝各位的閱讀!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI