1.HTML
<div class="frame">
<div class="center">
<div id="counter"></div>
<div id="pausebtn">
<div class="line"></div>
<div class="line"></div>
</div>
<div id="playbtn">
<div class="right-arrow"></div>
</div>
</div>
</div>
2.CSS
.frame {
position: absolute;
top: 50%;
left: 50%;
width: 400px;
height: 400px;
margin-top: -200px;
margin-left: -200px;
border-radius: 5px;
box-shadow: 4px 8px 16px 0 rgba(0, 0, 0, 0.1);
overflow: hidden;
background: #007193;
color: #333;
font-family: "Open Sans", Helvetica, sans-serif;
-webkit-font-smoothing: antialiased;
-moz-osx-font-smoothing: grayscale;
}
.center {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
}
#counter {
width: 125px;
height: 50px;
background: white;
border-radius: 10px;
color: #007193;
display: grid;
place-items: center;
font-size: 2em;
font-weight: 600;
letter-spacing: 0.1em;
user-select: none;
}
#pausebtn {
cursor: pointer;
display: flex;
margin-top: 10px;
margin-left: -5px;
align-items: center;
justify-content: center;
}
.line {
height: 25px;
width: 6px;
background: white;
margin-left: 5px;
}
#playbtn {
display: flex;
cursor: pointer;
align-items: center;
justify-content: center;
margin-top: 10px;
}
.right-arrow {
width: 0;
height: 0;
border-top: 15px solid transparent;
border-bottom: 15px solid transparent;
border-left: 25px solid white;
}
3.JS
let curNum = 0;
let paused = true;
const main = () => {
const counter = document.getElementById("counter");
counter.innerHTML = curNum.toString().padStart(4, 0);
const pausebtn = document.getElementById("pausebtn");
const playbtn = document.getElementById("playbtn");
pausebtn.style.display = "none";
playbtn.style.display = "flex";
pausebtn.addEventListener("click", () => {
paused = true;
pausebtn.style.display = "none";
playbtn.style.display = "flex";
});
playbtn.addEventListener("click", () => {
paused = false;
playbtn.style.display = "none";
pausebtn.style.display = "flex";
});
setInterval(() => {
if (!paused) {
curNum += 1;
counter.innerHTML = curNum.toString().padStart(4, 0);
}
}, 1000);
};
main();
3.运行结果
4.小结
这个案例时对计数器的一个简单运用,其中涉及HTML元素操作、事件监听和定时器。初始时,计数器curNum设为0,paused设为true表示暂停状态。main函数首先获取页面上的计数器元素和两个按钮元素,并设置按钮的初始显示状态。然后,为两个按钮添加点击事件监听器,点击暂停按钮将paused设为true并隐藏暂停按钮、显示播放按钮,点击播放按钮则相反。最后,设置一个每秒执行一次的定时器,当paused为false时,计数器加1并更新到页面上。整个应用实现了简单的计数器功能,可以通过按钮控制计数器的暂停和播放。