虽然HTML5已经定稿并且新的标准已经被推出来很久了,但是任然有浏览器开发公司在HTML5标准的基础上给大家提供更绚丽,更实用,更高用户体验的功能。W3C也同样的继续规范着HTML5的标准。
今天小编就给大家讲讲如何通过JavaScript获取电池状态,W3C获取电池状态api为我们详细介绍了api接口,并且有详细的demo实现。
电池管理状态接口如下:The BatteryManager interface
目前电池状态API是基于promise方式的API。这个API仍然是navigator对象提供的,叫做getBattery:
navigator.getBattery().then(function(result) {});
通过对getBattery()的调用,我们得到一个promise,这个promise会回调then方法,并提供一个BatteryManager对象,下面是对这个BatteryManager对象的说明:
// result: BatteryManagery { charging: false, chargingTime: Infinity, dischargingTime: 8940, level: 0.59, onchargingchange: null, onchargingtimechange: null, ondischargingtimechange: null, onlevelchange: null }
需要注意的是,这些API存在不兼容问题,需要在使用时加上浏览器前缀。
以下是事件处理程序(及其相应的事件处理程序的事件类型)必须支持的batterymanager对象属性:
event handler | event handler event type |
onchargingchange | chargingchange |
onchargingtimechange | chargingtimechange |
ondischargingtimechange | dischargingtimechange |
onlevelchange | levelchange |
相关例子如下:
// EXAMPLE 1 // We get the initial value when the promise resolves ... navigator.getBattery().then(function(battery) { console.log(battery.level); // ... and any subsequent updates. battery.onlevelchange = function() { console.log(this.level); }; }); // EXAMPLE 2 navigator.getBattery().then(function(battery) { console.log(battery.level); battery.addEventListener('levelchange', function() { console.log(this.level); }); }); // EXAMPLE 3 <!DOCTYPE html> <html> <head> <title>Battery Status API Example</title> <script> window.onload = function () { function updateBatteryStatus(battery) { document.querySelector('#charging').textContent = battery.charging ? 'charging' : 'not charging'; document.querySelector('#level').textContent = battery.level; document.querySelector('#dischargingTime').textContent = battery.dischargingTime / 60; } navigator.getBattery().then(function(battery) { // Update the battery status initially when the promise resolves ... updateBatteryStatus(battery); // .. and for any subsequent updates. battery.onchargingchange = function () { updateBatteryStatus(battery); }; battery.onlevelchange = function () { updateBatteryStatus(battery); }; battery.ondischargingtimechange = function () { updateBatteryStatus(battery); }; }); }; </script> </head> <body> <div id="charging">(charging state unknown)</div> <div id="level">(battery level unknown)</div> <div id="dischargingTime">(discharging time unknown)</div> </body> </html>
版权声明:本文为博主原创文章,未经博主允许不得转载。
: » 详解HTML5获取电池状态信息的方法
原创文章,作者:wure,如若转载,请注明出处:https://blog.ytso.com/251141.html