<!DOCTYPE html>
<html>
<head>
<meta charset="utf8">
<style>
:root {
--count-down-ring-size: 10em;
--count-down-ring-border: calc(var(--count-down-ring-size) / 2);
--count-down-ring-bg-color: lightgray;
--count-down-ring-fg-color: red;
}
.count-down-ring {
width: var(--count-down-ring-size);
height: var(--count-down-ring-size);
position: relative;
}
.count-down-left, .count-down-right {
width: 50%;
height: 100%;
position: absolute;
overflow: hidden;
}
.count-down-left, .count-down-left-ring {
left: 0;
}
.count-down-right, .count-down-right-ring {
/* 即使边框为0,两个div间还是会露出缝,因此 */
right: 1px;
}
.count-down-left-ring, .count-down-right-ring {
width: 200%;
height: 100%;
position: absolute;
border-width: var(--count-down-ring-border);
border-style: solid;
border-radius: 50%;
border-left-color: var(--count-down-ring-bg-color);
border-top-color: var(--count-down-ring-bg-color);
border-right-color: var(--count-down-ring-fg-color);
border-bottom-color: var(--count-down-ring-fg-color);
/* 这里必须采用border-box,把border限制在内部区域,否则会超出边界 */
box-sizing: border-box;
}
.count-down-left-ring {
transform: rotate(135deg);
animation: anim-count-down-left-ring 1s linear infinite;
display: block;
}
.count-down-right-ring {
transform: rotate(-45deg);
animation: anim-count-down-right-ring 1s linear infinite;
display: block;
}
@keyframes anim-count-down-left-ring {
from,50% {
transform: rotate(135deg);
}
/*50%, to {*/
to {
transform: rotate(-45deg);
}
}
@keyframes anim-count-down-right-ring {
/*from, 50% {*/
from {
transform: rotate(-45deg);
}
50%,to {
transform: rotate(-225deg);
}
}
.count-down-ring::after {
content: attr(data-content);
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
color: white;
font-size: calc(var(--count-down-ring-size) / 2);
font-weight: bold;
}
</style>
<script>
window.onload = ()=> {
const COUNTDOWN_MAX = 10;
let countdownValue = COUNTDOWN_MAX;
const countdowns = document.querySelectorAll(".count-down-ring");
const countdownId = setInterval(()=>{
countdownValue--;
if(countdownValue < 0) {
countdownValue = COUNTDOWN_MAX;
}
countdowns.forEach((countdown)=>{
//data-*和class属性在javascript里面会有一层特殊处理,分别存储到dataset和classList对象中(注意单词拼写与大小写)
countdown.setAttribute("data-content", countdownValue);
//countdown.dataset.content = countdownValue;
});
}, 1000);
};
</script>
</head>
<body>
<div class="count-down-ring" data-content="10">
<div class="count-down-left">
<div class="count-down-left-ring"></div>
</div>
<div class="count-down-right">
<div class="count-down-right-ring"></div>
</div>
</div>
<pre>
(1)当border-width较小的时候是圆环,当border-width较大的时候是整圆
(2)交换动画50%的位置(与from并列 或 与to并列)可以让动画的起始位置上下颠倒
当然,它还可以贴上背景图片,做游戏中的技能冷却按钮
</pre>
</body>
</html>
CSS3 倒计时 / 技能冷却
最新推荐文章于 2021-08-07 10:01:07 发布