Window:devicemotion 事件

Baseline 2023
Newly available

Since September 2023, this feature works across the latest devices and browser versions. This feature might not work in older devices or browsers.

安全上下文: 此项功能仅在一些支持的浏览器安全上下文(HTTPS)中可用。

devicemotion 事件每隔一定时间触发一次,显示设备当时在包括/不包括重力的作用下的加速度大小。如果有的话,它还会提供有关旋转速率的信息。

该事件不可取消,也不会冒泡。

语法

在类似于 addEventListener() 的方法中使用事件名,或设置事件处理器属性。

js
addEventListener("devicemotion", (event) => {});

ondevicemotion = (event) => {};

事件类型

事件属性

DeviceMotionEvent.acceleration 只读

给出设备在 x、y、z 三轴上的加速度。加速度用 m/s² 表示。

DeviceMotionEvent.accelerationIncludingGravity 只读

在重力作用下,给出设备在 x、y、z 三个轴上的加速度的对象。加速度单位为 m/s²

DeviceMotionEvent.rotationRate 只读

一个给出设备绕三个方向轴(阿尔法轴、贝塔轴和伽马轴)的旋转速率的对象。旋转速率以度每秒表示。

DeviceMotionEvent.interval 只读

代表从设备获取数据的时间间隔(毫秒)的数字。

示例

js
function handleMotionEvent(event) {
  const x = event.accelerationIncludingGravity.x;
  const y = event.accelerationIncludingGravity.y;
  const z = event.accelerationIncludingGravity.z;

  // 做点有意思的事情。
}

window.addEventListener("devicemotion", handleMotionEvent, true);

规范

Specification
Device Orientation and Motion
# devicemotion
Device Orientation and Motion
# ref-for-dom-window-ondevicemotion

浏览器兼容性

Report problems with this compatibility data on GitHub
desktopmobile
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
devicemotion event

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support

参见