Proximity Events - Web APIs 编辑

Experimental

This is an experimental technology
Check the Browser compatibility table carefully before using this in production.

The proximity events are a handy way to know when a user is close to a device. These events make it possible to react to such a change, for example by shutting down the screen of a smartphone when the user is having a phone call with the device close to their ear.

Note: Obviously, the API requires the device to have a proximity sensor, which are mostly available only on mobile devices. Devices without such a sensor may support those events but will never fire them.

Proximity Events

When the device proximity sensor detects a change between the device and an object, it notifies the browser of that change. When the browser gets such a notification, it fires a DeviceProximityEvent for any change, and a UserProximityEvent event in the case of a more rough change.

This event can be captured at the window object level by using the addEventListener method (using the deviceproximity or userproximity event name) or by attaching an event handler to the window.ondeviceproximity or window.onuserproximity properties.

Once captured, the event object gives access to different kinds of information:

  • The DeviceProximityEvent event provides an exact match for the distance between the device and the object through its value property. It also provides the closest and farthest distance the device is able to detect something through its min and max properties.
  • The UserProximityEvent event provides a rough approximation of the distance, expressed through a boolean. The UserProximityEvent.near property is true if the object is close or false if the object is far.

Example

window.addEventListener('userproximity', function(event) {
  if (event.near) {
    // let's power off the screen
    navigator.mozPower.screenEnabled = false;
  } else {
    // Otherwise, let's power on the screen
    navigator.mozPower.screenEnabled = true;
  }
});

Specifications

SpecificationStatusComment
Proximity Sensor
The definition of 'Proximity Events' in that specification.
Working DraftInitial specification

Browser compatibility

DeviceProximityEvent

BCD tables only load in the browser

UserProximityEvent

BCD tables only load in the browser

The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:107 次

字数:5536

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文