前端简单小秒杀

<!DOCTYPE html>
<html lang="en">
<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">
  <title>Document</title>
</head>
<body>
  <div id="seckill">
    <div class="seckill-countdown">
      <span>距离秒杀开始还有:</span>
      <span class="countdown-hour">00</span><span class="countdown-minute">00</span><span class="countdown-second">00</span></div>
    <button id="seckill-btn" disabled>秒杀</button>
  </div>
  
</body>
<script>
  // 获取秒杀模块的DOM元素
const seckillEl = document.querySelector('#seckill');

// 设置秒杀开始时间和结束时间(假设秒杀时间为每天10点到11点)
const startTime = new Date();
startTime.setHours(13, 0, 0, 0);
const endTime = new Date();
endTime.setHours(14, 0, 0, 0);

// 计算距离秒杀开始的时间,并更新页面上的倒计时显示
function updateCountdown() {
  const now = new Date();
  let timeLeft;
  if (now < startTime) {
    timeLeft = startTime - now;
    seckillEl.querySelector('.seckill-countdown').innerHTML = `
      <span>距离秒杀开始还有:</span>
      <span class="countdown-hour">${Math.floor(timeLeft / 1000 / 60 / 60)}</span>时
      <span class="countdown-minute">${Math.floor(timeLeft / 1000 / 60 % 60)}</span>分
      <span class="countdown-second">${Math.floor(timeLeft / 1000 % 60)}</span>秒
    `;
  } else if (now < endTime) {
    seckillEl.querySelector('.seckill-countdown').textContent = '秒杀进行中';
    seckillEl.querySelector('#seckill-btn').removeAttribute('disabled');
  } else {
    seckillEl.querySelector('.seckill-countdown').textContent = '秒杀已结束';
    seckillEl.querySelector('#seckill-btn').setAttribute('disabled', true);
  }
}

// 每秒钟更新一次倒计时
setInterval(updateCountdown, 1000);

</script>
</html>

 

posted @ 2023-04-25 14:41  Zhaiew  阅读(15)  评论(0)    收藏  举报