h5 -> 手机重力感应/摇一摇

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge,chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no"/>
<meta name="format-detection"content="telephone=no">
<title>html5重力感应事件</title>
</head>
<body>
    <p>摇一摇去触发html5重力感应事件</p>
	
	<div id="j"></div>
    <script type="text/javascript">
    	if (window.DeviceMotionEvent) { 
            window.addEventListener('devicemotion',deviceMotionHandler, false);  
        } 
        var speed = 1;//速度
        var x = y = z = lastX = lastY = lastZ = 0;
        function deviceMotionHandler(eventData) {  
          var acceleration =eventData.accelerationIncludingGravity;
                x = acceleration.x;
                y = acceleration.y;
                z = acceleration.z;
				
				//document.getElementById("j").innerHTML = "\n "+Math.abs(x-lastX)+"\n"+Math.abs(y-lastY)+"\n"+Math.abs(z-lastZ);
                if(Math.abs(x-lastX) > speed || Math.abs(y-lastY) > speed || Math.abs(z-lastZ) > speed) {
                    //简单的摇一摇触发代码
                    //alert('触发了重力感应');
					document.getElementById("j").innerHTML = "\n "+Math.abs(x-lastX);
                }
                lastX = x;
                lastY = y;
                lastZ = z;
        }
    </script>

</body>
</html>

参考:

http://www.haorooms.com/post/html5_DeviceMotionEvent

猜你喜欢

转载自mft.iteye.com/blog/2390136