BatteryManager:chargingchange 事件

Limited availability

This feature is not Baseline because it does not work in some of the most widely-used browsers.

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

BatteryManager 接口的 chargingchange 事件在电池的 charging 属性更新时触发。

语法

addEventListener() 等方法中使用事件名称,或设置事件处理器属性。

js
addEventListener("chargingchange", (event) => { })

onchargingchange = (event) => { }

事件类型

一个通用的 Event

示例

HTML

html
<div id="level">(电池电量未知)</div>
<div id="chargingTime">(电池充电时间未知)</div>

JavaScript

js
navigator.getBattery().then((battery) => {
  battery.onchargingchange = () => {
    document.querySelector("#level").textContent = battery.level;
    document.querySelector("#chargingTime").textContent = battery.chargingTime;
  };
});

规范

Specification
Battery Status API
# ref-for-dfn-chargingchange-1
Battery Status API
# dom-batterymanager-onchargingchange

浏览器兼容性

BCD tables only load in the browser

参见