今天要來分享我看 Youtube 影片做出來的 timer,
照慣例先放影片連結,
用他裡面提到的觀念延伸做出我這個 timer。
HTML
<div class="timer">
<div class="time">
<span id="minute">00</span>:<span id="second">00</span>
</div>
<svg width="300" height="300">
<circle id="circle1" cx="150" cy="150" r="120"></circle>
<circle id="circle2" cx="150" cy="150" r="120"></circle>
</svg>
</div>
<button id="button">START</button>
<button id="reset">RESET</button>
CSS
@import url('https://fonts.googleapis.com/css2?family=Space+Mono:wght@400;700&display=swap');
*{
margin: 0;
padding: 0;
list-style:none;
line-height: 1;
box-sizing: border-box;
}
body{
background-color: #1b262c;
text-align:center;
font-family: 'Space Mono', monospace;
}
.timer{
position: relative;
}
.time {
position: absolute;
left: 50%;
top: 50%;
transform: translate(-50%, -50%)
}
.time{
font-size: 40px;
color: #fff;
}
svg{
display: inline-block;
vertical-align: middle;
}
circle{
stroke-width: 5px;
fill: transparent;
stroke-linecap: round;
}
#circle1{
stroke: rgba(0,0,0, .4);
}
#circle2{
stroke:#bbe1fa;
transition: 1s linear;
}
button{
vertical-align: middle;
width: 80px;
padding: 10px;
margin: 0;
color: #fff;
border: none;
border-radius: 5px;
cursor: pointer;
font-family: 'Space Mono', monospace;
}
button:focus{
outline:none;
}
button:active{
box-shadow: inset 0px 0px 1px 2px #1b262c;
}
#button{
background-color: #0f4c75;
}
#reset{
background-color: #3282b8;
}
JS
const circle = document.getElementById('circle2');
const button = document.getElementById('button');
const reset = document.getElementById('reset')
const length = circle.getTotalLength();
const minute = document.getElementById('minute');
const second = document.getElementById('second');
circle.style.strokeDasharray = length;
circle.style.strokeDashoffset = length;
let count = 0;
let timer;
let isPlaying = false;
button.addEventListener('click',
function() {
isPlaying = !isPlaying;
if(isPlaying){
startTimer();
}else{
stopTimer();
}
}
);
reset.addEventListener('click', resetTimer);
function startTimer(){
button.textContent = "STOP";
timer = setInterval(function(){
count++;
minute.textContent = (Math.floor(count / 60) < 10 ? '0' : '') + Math.floor(count / 60) ;
second.textContent = (count % 60 < 10 ? '0' : '') + count % 60 ;
circle.style.strokeDashoffset = length - (count / 60) * length;
},1000)
}
function stopTimer(){
console.log('stopTimer');
clearInterval(timer);
button.textContent = "START";
}
function resetTimer(){
stopTimer();
count = 0;
minute.textContent = '00';
second.textContent = '00'
circle.style.strokeDashoffset = length;
isPlaying = false;
}
也直接附上我的 codepen,
今天就先到這裡啦~
我們明天見。