728x90
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<script>
document.addEventListener('DOMContentLoaded', () => {
const checkbox=document.querySelector('input')
const h1 = document.querySelector('h1')
let seconds=0
let id
checkbox.addEventListener('click',(e)=>{
if(e.currentTarget.checked){
id = setInterval(()=>{
seconds++
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const remainingSeconds = seconds % 60;
h1.textContent=`${hours > 0 ? hours + '시간 ' : ''}${minutes > 0 ? minutes + '분 ' : ''}${remainingSeconds}초`;
},1000)
}else{
clearInterval(id)
}
})
})
</script>
<body>
<input type="checkbox">
<span>공부 시작</span>
<h1></h1>
</body>
</html>
XX 시간 XX 분 XX초 나오게 하였다.
만약 시간을 더블클릭할 경우 0으로 돌아가게 하면 다음과 같다.
<!DOCTYPE html>
<html lang="ko">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<script>
document.addEventListener('DOMContentLoaded', () => {
const checkbox = document.querySelector('input')
const h1 = document.querySelector('h1')
let seconds = 0
let id
checkbox.addEventListener('click', (e) => {
if (e.currentTarget.checked) {
id = setInterval(() => {
seconds++
const hours = Math.floor(seconds / 3600);
const minutes = Math.floor((seconds % 3600) / 60);
const remainingSeconds = seconds % 60;
h1.textContent = `${hours > 0 ? hours + '시간 ' : ''}${minutes > 0 ? minutes + '분 ' : ''}${remainingSeconds}초`;
}, 1000)
} else {
clearInterval(id)
}
})
h1.addEventListener('dblclick', () => {
clearInterval(id);
seconds = 0;
h1.textContent = "0초";
});
})
</script>
<body>
<input type="checkbox">
<span>공부 시작</span>
<h1></h1>
</body>
</html>
728x90