做一個倒數計時器。
STEP1 取得頁面元素和宣告變數
let countdown;
const timerDisplay = document.querySelector('.display__time-left');
const endTime = document.querySelector('.display__end-time');
const buttons = document.querySelectorAll('[data-time]');
**STEP2 **
function timer(seconds){
// clear any existing timers
clearInterval(countdown);
const now = Date.now();
const then = now + seconds * 1000 //Date取得為minsec
displayTimeLeft(seconds);
displayEndTime(then);
countdown = setInterval(()=>{
const secondsLeft = Math.floor((then - Date.now()) / 1000);
// check if we should stop it!
if (secondsLeft < 0) {
clearInterval(countdown);
return;
}
// display it
displayTimeLeft(secondsLeft);
}, 1000);
}
**STEP3 **
function displayTimeLeft(seconds){
const minutes = Math.floor(seconds / 60);
const reminderSeconds = seconds % 60;
const display = `${minutes}:${remainderSeconds < 10 ? '0' : '' }${remainderSeconds}`;
document.title = display;
timerDisplay.textContent = display;
}
**STEP4 **
function displayEndTime(timestamp) {
const end = new Date(timestamp);
const hour = end.getHours();
const adjustedHour = hour > 12 ? hour -12 : hour;
const minutes = end.getMinutes();
endTime.textContent = `Be Back At ${adjustedHour}:${minutes < 10 ? '0' : ''}${minutes}`;
}
**STEP5 **
function startTimer() {
const seconds = parseInt(this.dataset.time);
timer(seconds);
}
buttons.forEach(button => button.addEventListener('click', startTimer));
document.customForm.addEventListener('submit', function(e){
e.preventDefault();
const mins = this.minutes.value;
timer(mins *60);
this.reset();
})
做一個打地鼠的遊戲。
STEP1 取得頁面元素和宣告變數
const holes = document.querySelectorAll('.hole');
const scoreBoard = document.querySelector('.score');
const moles = document.querySelectorAll('.mole');
let lastHole;
let timeUp = false;
let score = 0;
**STEP2 **
function randomTime(min, max){
return Math.round(Math.random() * (max-min) + min);
}
function randomHole(holes){
// console.log(holes);
const idx = Math.floor(Math.random() * holes.length);
const hole = holes[idx];
if(hole === lastHole){
return randomHole(holes);
}
lastHole = hole;
return hole;
}
function peep(){
const time = randomTime(20, 1000);
const hole = randomHole(holes);
hole.classList.add('up');
setTimeout(()=>{
hole.classList.remove('up');
if (!timeUp) peep();
}, time);
}
**STEP3 **
function startGame(){
score = 0
scoreBoard.textContent = score;
timeUp = false;
peep();
setTimeout(()=> timeUp = true, 10000);
}
**STEP4 **
function bonk(e){
if(!e.isTrusted) return
score++;
this.parentNode.classList.remove('up');
scoreBoard.textContent = score;
}
moles.forEach(mole => mole.addEventListener('click', bonk));