HTML
<div class="zib-widget">
<div class="text-center">
<h3>电池</h3>
<div class="batteryShape">
<div class="level">
<div class="percentage" style="width: 100%;">
</div>
</div>
</div>
<div class="percent">100%</div>
<p class="batteryTime">正在充电</p>
</div>
</div>
CSS
/*电池电量*/
.batteryShape{
position: relative;
width: 140px;
height: 65px;
margin: auto;
border: 3px solid #333;
border-radius: 10px;
}
.batteryShape::before{
content: '';
position: absolute;
top: 50%;
right: -12px;
margin-left: 2px;
transform: translateY(-50%);
width: 7px;
height: 16px;
background: #333;
border-top-right-radius: 4px;
border-bottom-right-radius: 4px;
}
.batteryShape::after{
content: '';
position: absolute;
top: 0;
left: 0;
width: 100%;
height: 50%;
background: rgba(255,255,255,.1);
}
.level{
position: absolute;
top: 4px;
right: 4px;
bottom: 4px;
left: 4px;
border-radius: 4px;
overflow: hidden;
}
.percentage{
position: absolute;
top: 0;
left: 0;
height: 100%;
width: 50%;
background: linear-gradient(90deg,#9c27b0,#fd2c72);
}
.batteryTime{
font-size: 0.6em;
color: #333333;
letter-spacing: -0.6px;
}
JavaScript
// 充电状态
var pt = document.querySelector('.percentage');
var p = document.querySelector('.percent');
//获取电池状态
navigator.getBattery().then(function(battery) {
//初始化电量
pt.style.width = battery.level * 100 + "%";
p.innerHTML = battery.level * 100 + "%"
//监听电量变化
battery.addEventListener("levelchange", function (e) {
console.log("电量水平变化: ", battery.level);
pt.style.width = battery.level * 100 + "%";
p.innerHTML = battery.level * 100 + "%"
}, false);
//初始化电池状态变化
var charging = battery.charging ? "yes" : "no";
if (charging === "yes"){
document.querySelector('.batteryTime').innerHTML = '正在充电';
}else {
document.querySelector('.batteryTime').innerHTML = '未在充电';
}
//监听电池充电状态变化
battery.addEventListener("chargingchange", function (e) {
console.warn("电池充电状态变化: ", battery.charging);
var cd = battery.charging?'yes':'no';
if (cd == 'yes'){
document.getElementsByClassName('batteryTime')[0].innerHTML = '正在充电';
}else {
document.getElementsByClassName('batteryTime')[0].innerHTML = '未在充电';
}
}, false);
});
没有回复内容