js控制电池

  1. 判断设备是否在充电

    navigator.getBattery().then(function(battery){
    if(battery.charging) {
    alert("电池正在充电");
    }else {
    alert("电池没有充电");
    }
    })
  2. 获取设备电量

    navigator.getBattery().then(function(battery){
    alert("电池电量" + battery.level * 100 + "%");
    })
  3. 电池状态监听器

    navigator.getBattery().then(function(battery){
    battery.addEventListener("chargingchange", function() {
    console.log("电池状态:", battery.charging);
    }) battery.addEventListener("levelchange", function() {
    console.log("电池电量:", battery.level * 100 + "%");
    }) battery.addEventListener("chargingtimechange", function() {
    console.log("电池充满还需:", battery.chargingTime + "秒");
    }) battery.addEventListener("dischargingtimechange", function() {
    console.log("电池电量还能支撑:", battery.dischargingTime + "秒");
    })
    })
05-17 15:12