Skip to content

Instantly share code, notes, and snippets.

@Nyaasu66
Created April 23, 2023 08:34
Show Gist options
  • Save Nyaasu66/0788946236d55167497121e04ca4f53b to your computer and use it in GitHub Desktop.
Save Nyaasu66/0788946236d55167497121e04ca4f53b to your computer and use it in GitHub Desktop.
显示设备电量/充电状态,单 html 文件
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>My battery level</title>
</head>
<body>
<div id="battery">
<div id="level">
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24">
<path d="M13 10H20L11 23V14H4L13 1V10Z"></path>
</svg>
<span id="value"></span>
</div>
</div>
<script>
const $battery = document.getElementById('battery');
const $level = document.getElementById('level');
const $value = document.getElementById('value');
navigator.getBattery().then((battery) => {
const update = () => {
const { charging, level } = battery;
if (charging) {
$battery.dataset.charging = 'true';
} else {
delete $battery.dataset.charging;
}
$level.style.setProperty('--level', level);
$value.textContent = Math.round(level * 100) + '%';
};
update();
battery.addEventListener('levelchange', () => {
update();
});
battery.addEventListener('chargingchange', () => {
update();
});
});
</script>
<style>
body {
height: 100vh;
margin: 0;
display: grid;
place-content: center;
font-family: Inter, Segoe UI, sans-serif;
background: black;
}
#battery {
width: 50vw;
height: 15vw;
border: 1vw solid #6b7280;
border-radius: 1.5vw;
position: relative;
}
#battery::after {
content: '';
display: block;
height: 5vw;
width: 1vw;
border-top-right-radius: 0.5vw;
border-bottom-right-radius: 0.5vw;
background: #6b7280;
position: absolute;
left: 100%;
top: 0;
bottom: 0;
margin: auto;
margin-left: 1vw;
}
#level {
height: 100%;
font-size: 5vw;
border-radius: 0.5vw;
overflow: hidden;
position: relative;
display: flex;
justify-content: center;
align-items: center;
}
#level::before {
content: '';
display: block;
width: calc(var(--level) * 100%);
height: 100%;
background: #4ade80;
position: absolute;
top: 0;
left: 0;
}
svg {
width: 1em;
height: 1em;
fill: white;
filter: drop-shadow(1px 1px 2px #000);
display: none;
}
#battery[data-charging] svg {
display: block;
}
#level span {
font-weight: bold;
color: white;
text-shadow: 1px 1px 4px #000;
position: relative;
}
</style>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment