使用JavaScript实现带时间间隔的记录集逐次切换功能
实现按倒计时切换问题记录的方案
1. 基础样式设置
先确保HTML、body和.area的样式满足全屏且隐藏溢出的要求:
html, body { height: 100%; margin: 0; padding: 0; overflow: hidden; } .area { width: 100%; height: 100%; overflow: hidden; position: absolute; top: 0; left: 0; display: none; /* 默认隐藏所有区域 */ } .area.active { display: block; /* 只显示当前激活的区域 */ }
2. PHP查询并渲染记录
连接数据库,查询question表的所有记录,循环生成每个.area区域,每个区域包含倒计时器和问题内容:
<?php // 数据库连接配置 $servername = "localhost"; $username = "your_username"; $password = "your_password"; $dbname = "your_dbname"; // 创建连接 $conn = new mysqli($servername, $username, $password, $dbname); // 检查连接 if ($conn->connect_error) { die("连接失败: " . $conn->connect_error); } // 查询question表 $sql = "SELECT id, content, countdown_time FROM question"; $result = $conn->query($sql); if ($result->num_rows > 0) { $index = 0; // 输出数据 while($row = $result->fetch_assoc()) { // 第一个区域默认激活 $activeClass = $index === 0 ? 'active' : ''; echo '<div class="area ' . $activeClass . '" data-time="' . $row["countdown_time"] . '">'; echo '<h3>问题 ' . ($index+1) . '</h3>'; echo '<p>' . $row["content"] . '</p>'; echo '<div class="countdowntimer" id="countdowntimer-' . $index . '">' . $row["countdown_time"] . '</div>'; echo '</div>'; $index++; } } else { echo '<div class="area active">暂无问题记录</div>'; } $conn->close(); ?>
注意:这里给每个.area添加了data-time属性存储倒计时时长,每个倒计时器用唯一ID区分,避免冲突。
3. JavaScript实现倒计时与切换逻辑
编写JS代码,实现倒计时功能,当当前区域倒计时归0时,切换到下一个区域:
document.addEventListener('DOMContentLoaded', function() { const areas = document.querySelectorAll('.area'); let currentIndex = 0; let timer; // 启动倒计时函数 function startCountdown(index) { const currentArea = areas[index]; const countdownEl = currentArea.querySelector('.countdowntimer'); let time = parseInt(currentArea.dataset.time); // 清除之前的定时器 if (timer) clearInterval(timer); timer = setInterval(function() { time--; countdownEl.innerHTML = time; if (time <= 0) { clearInterval(timer); // 切换到下一个区域 switchToNextArea(); } }, 1000); } // 切换区域函数 function switchToNextArea() { // 隐藏当前区域 areas[currentIndex].classList.remove('active'); // 计算下一个索引,循环切换 currentIndex = (currentIndex + 1) % areas.length; // 显示下一个区域 areas[currentIndex].classList.add('active'); // 启动新区域的倒计时 startCountdown(currentIndex); } // 初始化启动第一个区域的倒计时 startCountdown(currentIndex); });
关键说明
- 每个
.area区域默认隐藏,只有添加active类的区域才会显示 - 用
data-time属性存储每个问题对应的倒计时时长,灵活控制不同问题的展示时间 - 倒计时结束后自动切换到下一个区域,到达最后一个后会循环回到第一个
- 每个区域的倒计时器使用独立的选择器,避免ID冲突问题
内容的提问来源于stack exchange,提问作者radityo nugroho
相关产品推荐
相关产品推荐

