HTML中可以使用battery API來獲取并設置設備的電量信息。首先需要在html的head標簽中添加如下代碼引用該API:
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://batteryapi.com/batteryapi.js"></script>
接著在body標簽中定義一個div元素,并在其中加入如下代碼:
<div>
<label>Battery Level:</label>
<progress id="battery-level" max="100" value="0"></progress>
<span id="battery-percentage"></span>
</div>
該代碼定義了一個進度條和一個span元素,用于顯示設備的電池電量信息。
接著需要編寫一段JavaScript代碼來實現電池電量的實時更新:
$().ready(function(){
if("getBattery" in navigator){
navigator.getBattery().then(function(battery){
updateBatteryLevel(battery);
battery.addEventListener("levelchange", function(){
updateBatteryLevel(battery);
});
});
}
function updateBatteryLevel(battery){
$("#battery-level").val(battery.level * 100);
$("#battery-percentage").text((battery.level * 100) + "%");
}
});
該代碼首先檢查瀏覽器是否支持battery API,然后通過getBattery方法獲取設備的電池信息,再通過addEventListener方法監聽設備電量變化的事件并調用updateBatteryLevel函數來更新電量信息。
最后附上一個完整的HTML代碼作為示例:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Battery Level</title>
<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
<script src="https://batteryapi.com/batteryapi.js"></script>
</head>
<body>
<div>
<label>Battery Level:</label>
<progress id="battery-level" max="100" value="0"></progress>
<span id="battery-percentage"></span>
</div>
<script>
$().ready(function(){
if("getBattery" in navigator){
navigator.getBattery().then(function(battery){
updateBatteryLevel(battery);
battery.addEventListener("levelchange", function(){
updateBatteryLevel(battery);
});
});
}
function updateBatteryLevel(battery){
$("#battery-level").val(battery.level * 100);
$("#battery-percentage").text((battery.level * 100) + "%");
}
});
</script>
</body>
</html>