需求:頁面無操作時每隔一段時間隨機顯示一個 7 位數;用戶操作(點擊、輸入等)時停止隨機,顯示指定的 7 位數。
setInterval 定時生成隨機數並更新 DOM。mousemove、keydown、click、touchstart)。<div id="numberDisplay" style="font-size: 2rem; font-family: monospace;">--</div>
<script>
const display = document.getElementById('numberDisplay');
const SPECIFIED_NUMBER = '8888888'; // 指定的 7 位數
const INTERVAL_MS = 2000; // 隨機切換間隔
let timerId = null;
let hasInteracted = false;
// 生成 7 位隨機數(首位非 0)
function genRandom7() {
return Math.floor(1000000 + Math.random() * 9000000).toString();
}
// 開始隨機輪播
function startRandom() {
display.textContent = genRandom7();
timerId = setInterval(() => {
display.textContent = genRandom7();
}, INTERVAL_MS);
}
// 停止隨機,顯示指定數字
function stopRandomAndShowSpecified() {
if (hasInteracted) return; // 防重複
hasInteracted = true;
clearInterval(timerId);
display.textContent = SPECIFIED_NUMBER;
// 可選:移除事件監聽器
['mousemove', 'keydown', 'click', 'touchstart'].forEach(evt => {
document.removeEventListener(evt, stopRandomAndShowSpecified);
});
}
// 綁定交互事件(捕獲階段,優先觸發)
['mousemove', 'keydown', 'click', 'touchstart'].forEach(evt => {
document.addEventListener(evt, stopRandomAndShowSpecified, true);
});
// 啟動
startRandom();
</script>
Math.floor(1000000 + Math.random() * 9000000) 確保生成 7 位數(1000000~9999999)。hasInteracted 標誌位防止多次清除定時器/移除監聽器報錯。capture: true(第三參數),確保在冒泡前優先攔截,響應更及時。touchstart 事件。window.addEventListener('blur', () => {
if (hasInteracted) {
hasInteracted = false;
startRandom();
// 重新綁定事件...
}
});
此模式常用於驗證碼展示、動態數據大屏、防機器人檢測等場景。