JavaScript 练习根据点击事件切换时间倒计时

刚学习完JavaScript的伙伴们可以通过小的案列练习一下,才能巩固知识,让你的编程水平成为班级最牛的人。

1.html结构

<div id="timer-message">Please select a timer before starting.</div>

    <div class="container">
          <div class="timer">
            <h1>🍅 Pomodoro Timer</h1>
    
            <div class="button-container">
              <button class="button" id="pomodoro-session">Pomodoro</button>
              <button class="button" id="short-break">Short Break</button>
              <button class="button" id="long-break">Long break</button>
            </div>
    
            <div id="pomodoro-timer" class="timer-display" data-duration="25.00">
              25:00
            </div>
    
            <div id="short-timer" class="timer-display" data-duration="5.00">
              5:00
            </div>
    
            <div id="long-timer" class="timer-display" data-duration="10.00">
              10:00
            </div>
    
            <div id="buttons">
              <button id="start">开始</button>
              <button id="stop">暂停</button>
            </div>
          </div>
        </div>

2.css样式

body {
    background-color: #1e213f;
    color: #d7e0ff;
}
  .container {
    text-align: center;
    width: 100%;
    padding: 10px 0;
  }
  
  .timer {
    display: inline-block;
    padding: 10px;
    width: 600px;
    box-sizing: border-box;
  }
  h1 {
    font-size: 2em;
    width: 8ch;
    margin: 20px auto;
  }
  .button-container {
    margin-top: 20px;
    display: flex;
    justify-content: center;
  }
  .button {
    background-color: #2e325a;
    color: #fff;
    border: none;
    border-radius: 5px;
    padding: 10px 20px;
    margin: 5px;
    cursor: pointer;
  }
  .button:hover {
    background-color: #f87070;
  }
  .hidden {
    display: block;
  }
  .timer-display {
    font-size: 5em;
    margin-top: 20px;
    font-weight: bold;
  }
  #buttons {
    margin-top: 20px;
  }
  #start,
  #stop {
    background-color: #2e325a;
    color: #fff;
    border: none;
    border-radius: 5px;
    padding: 10px 20px;
    margin: 10px;
    /* 手型 */
    cursor: pointer;  
  }
  
  #stop:hover {
    background-color: tomato;
  }
  #start:hover {
    background-color: #219a52;
  }
   #timer-message {
     color: white;
     background-color: tomato;
     display: none;
     padding: .5em;
     font-size: 1em;
     text-align: center;
     border-radius: 1em;
    }

3.js部分
 

流程分析:

1. 获取时间节点  

let pomodoro = document.getElementById("pomodoro-timer");
let short = document.getElementById("short-timer");
let long = document.getElementById("long-timer");

 

2.封装时间显示与隐藏

function showDefaultTimer() {
    pomodoro.style.display = "block";
    short.style.display = "none";
    long.style.display = "none";
   }
   
 showDefaultTimer()

3.获取button 遍历按钮,创建事件侦听器,用于侦听每个计时器按钮中的单击事件。首先声明一个变量,并将其值设置为 null。将指定当前正在运行的计时器。currentTimercurrentTimer

(1).遍历按钮

function hideAll(){
    let timers = document.querySelectorAll(".timer-display");
    timers.forEach(timer=> timer.style.display ="none")  
};

 (2)获取点击事件切换



 let currentTimer =null;
接下来,创建事件侦听器,当用户单击按钮时将触发该侦听器。

document.getElementById("pomodoro-session").addEventListener("click", function(){
    hideAll();  //调用函数
    pomodoro.style.display = "block"
    currentTimer = pomodoro   
});
document.getElementById("short-break").addEventListener("click", function(){
    hideAll();
    short.style.display = "block"
    currentTimer =short
 
});
document.getElementById("long-break").addEventListener("click", function(){
    hideAll();
    
    long.style.display = "block"
    currentTimer =long
    
});

完整js代码

// 定义一个空的常量
let myInterval = null;

//使用剩余时间并每 1 秒(1000 毫秒)运行一次,直到剩余时间用完,使用每秒的剩余时间更新我们的显示。当计时器达到 0 时,我们将显示 00:00 并播放警报声

function startTimer(timerdisplay) {
    if (myInterval) {
        clearInterval(myInterval);
    }

    timerDuration = timerdisplay
        .getAttribute("data-duration")
        .split(":")[0];
    console.log(timerDuration);

    let durationinmiliseconds = timerDuration * 60 * 1000;
    let endTimestamp = Date.now() + durationinmiliseconds;
      //Window 和 Worker 接口提供的 setInterval() 方法重复调用一个函数或执行一个代码片段,在每次调用之间具有固定的时间间隔。
    myInterval = setInterval(function () {
        const timeRemaining = new Date(endTimestamp - Date.now());
        console.log(myInterval)
        if (timeRemaining <= 0) {
            clearInterval(myInterval);
            timerdisplay.textContent = "00:00";
            const alarm = new Audio(
                "https://www.freespecialeffects.co.uk/soundfx/scifi/electronic.wav"
            );
            alarm.play();
        } else {
            const minutes = Math.floor(timeRemaining / 60000);
            const seconds = ((timeRemaining % 60000) / 1000).toFixed(0);
            const formattedTime = `${minutes}:${seconds
                .toString()
                .padStart(2, "0")}`;
            console.log(formattedTime);
            timerdisplay.textContent = formattedTime;
        }
    }, 1000);
}

document.getElementById("start").addEventListener("click", function () {
    if (currentTimer) {
        startTimer(currentTimer);
        document.getElementById("timer-message").style.display = "none";
    } else {
        document.getElementById("timer-message").style.display = "block";
    }
});

document.getElementById("stop").addEventListener("click", function () {
    if (currentTimer) {
        clearInterval(myInterval);
    }
});

如果想提升你的编程水平就多加练习吧,在编程中碰到BUG也不要着急。有解决不了的问题可以加我的qq:2415714416。有需要毕设或是期末作业,我会满足您的需求的? 

 

  • 10
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值