# 检测设备方向

## 处理方向（orientation）事件

js
``````window.addEventListener("deviceorientation", handleOrientation, true);
``````

`DeviceOrientationEvent.absolute` `DeviceOrientationEvent.alpha` `DeviceOrientationEvent.beta` `DeviceOrientationEvent.gamma`

js
``````function handleOrientation(orientData) {
var absolute = orientData.absolute;
var alpha = orientData.alpha;
var beta = orientData.beta;
var gamma = orientData.gamma;

// Do stuff with the new orientation data
}
``````

### 示例

html
``````<div class="garden">
<div class="ball"></div>
</div>

<pre class="output"></pre>
``````

css
``````.garden {
position: relative;
width: 200px;
height: 200px;
border: 5px solid #ccc;
}

.ball {
position: absolute;
top: 90px;
left: 90px;
width: 20px;
height: 20px;
background: green;
}
``````

js
``````var ball = document.querySelector(".ball");
var garden = document.querySelector(".garden");
var output = document.querySelector(".output");

var maxX = garden.clientWidth - ball.clientWidth;
var maxY = garden.clientHeight - ball.clientHeight;

function handleOrientation(event) {
var x = event.beta; // In degree in the range [-180,180]
var y = event.gamma; // In degree in the range [-90,90]

output.innerHTML = "beta : " + x + "\n";
output.innerHTML += "gamma: " + y + "\n";

// Because we don't want to have the device upside down
// We constrain the x value to the range [-90,90]
if (x > 90) {
x = 90;
}
if (x < -90) {
x = -90;
}

// To make computation easier we shift the range of
// x and y to [0,180]
x += 90;
y += 90;

// 10 is half the size of the ball
// It center the positioning point to the center of the ball
ball.style.top = (maxX * x) / 180 - 10 + "px";
ball.style.left = (maxY * y) / 180 - 10 + "px";
}

``````

## 处理移动（motion）事件

js
``````window.addEventListener("devicemotion", handleMotion, true);
``````

### 相关值解释

`DeviceMotionEvent`对象提供给 web 开发者设备在位置和方向上的改变速度的相关信息。这些变化信息是通过三个轴来体现的。（Orientation and motion data explained有更详细的说明。）

• `x`: 西向东
• `y`: 南向北
• `z`: 垂直地面

• `alpha`: 设备沿着垂直于屏幕（对于桌面设备则是垂直于键盘）的轴的旋转速率
• `beta`: 设备沿着屏幕（对于桌面设备则是键盘）左至右方向的轴的旋转速率 (桌面设备相对于键盘)
• `gamma`: 设备沿着屏幕（对于桌面设备则是键盘）下至上方向的轴的旋转速率

## 浏览器兼容性

### api.DeviceMotionEvent

BCD tables only load in the browser

### api.DeviceOrientationEvent

BCD tables only load in the browser