html 5 흔 들 기 기능 실현

원리:DeviceMotion 을 사용 하여 이 루어 집 니 다.DeviceMotion 에 대한 소 개 는 볼 수 있 습 니 다.https://developer.mozilla.org/en-US/docs/Web/Reference/Events/devicemotion
DeviceMotionEvent 를 통 해 acceleration Including Gravity 의 x,y,z 속성 을 얻 을 수 있 으 며 x,y,z 속성의 변화 에 따라 장치 가 흔 들 리 는 사건 이 발생 했 는 지 판단 할 수 있 습 니 다.
가속도 IncludeingGravity 설명:장치 의 가속도.이 값 은 중력 효 과 를 포함 하 며,자 이 로 스 코 프 가 없 는 장치 에서 사용 할 수 있 는 유일한 값 일 수 있 습 니 다.
코드 는 다음 과 같 습 니 다:
<!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">
    <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>

좋은 웹페이지 즐겨찾기