CSS 和 JS 实现广告页倒计时

172 阅读1分钟

在很多应用或网站里,启动页或广告页通常会有一个倒计时功能。以下是一个简单的示例,展示如何用 HTML、CSS 和 JavaScript 实现一个3秒倒计时的广告页。

HTML 结构

<div class="ad-container">
  <div class="ad-content">
    <img src="your-ad-image.jpg" alt="广告图片" />
  </div>
  <div class="countdown" id="countdown">3</div>
</div>

CSS 样式

.ad-container {
  position: relative;
  width: 100%;
  height: 100vh;
  background-color: #fff;
}

.ad-content {
  width: 100%;
  height: 100%;
}

.ad-content img {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.countdown {
  position: absolute;
  top: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.5);
  color: #fff;
  padding: 10px;
  border-radius: 50%;
  font-size: 18px;
  z-index: 1;
}

JavaScript 代码

document.addEventListener("DOMContentLoaded", function () {
  const countdownElement = document.getElementById("countdown");
  let countdown = 3;

  const interval = setInterval(function () {
    countdown -= 1;
    countdownElement.textContent = countdown;

    if (countdown === 0) {
      clearInterval(interval);
      // 这里可以添加代码来关闭广告或者跳转到其他页面
      // 例如:
      // window.location.href = "your-next-page.html";
    }
  }, 1000);
});

在这个示例中,ad-container 是广告的容器,ad-content 是广告内容(这里用一个图片代替),countdown 是显示倒计时的元素。

JavaScript 代码会在页面加载完成后开始一个倒计时。每秒减少1,直到倒计时结束。当倒计时结束时,你可以选择关闭广告或者跳转到其他页面。

这只是一个简单的示例,你可以根据需要进一步定制。