九宮格抽獎是一種常見的互動游戲,通常用于營銷活動或娛樂場景。本文將介紹如何使用原生JavaScript實現一個簡單的九宮格抽獎功能。
九宮格抽獎的核心邏輯是讓一個“指針”在九宮格中隨機移動,最終停留在某個格子上。我們可以通過以下步驟來實現:
首先,我們需要創建一個簡單的HTML結構來表示九宮格:
<div id="grid">
<div class="cell" data-index="0">1</div>
<div class="cell" data-index="1">2</div>
<div class="cell" data-index="2">3</div>
<div class="cell" data-index="3">4</div>
<div class="cell" data-index="4">5</div>
<div class="cell" data-index="5">6</div>
<div class="cell" data-index="6">7</div>
<div class="cell" data-index="7">8</div>
<div class="cell" data-index="8">9</div>
</div>
<button id="start">開始抽獎</button>
接下來,我們使用CSS來美化九宮格:
#grid {
display: grid;
grid-template-columns: repeat(3, 100px);
grid-template-rows: repeat(3, 100px);
gap: 10px;
}
.cell {
display: flex;
justify-content: center;
align-items: center;
background-color: #f0f0f0;
border: 1px solid #ccc;
font-size: 24px;
cursor: pointer;
}
.cell.active {
background-color: #ffcc00;
}
最后,我們使用JavaScript來實現抽獎邏輯:
const cells = document.querySelectorAll('.cell');
const startButton = document.getElementById('start');
let currentIndex = 0;
let intervalId;
function highlightCell(index) {
cells.forEach(cell => cell.classList.remove('active'));
cells[index].classList.add('active');
}
function startLottery() {
clearInterval(intervalId);
intervalId = setInterval(() => {
currentIndex = (currentIndex + 1) % cells.length;
highlightCell(currentIndex);
}, 100);
}
function stopLottery() {
clearInterval(intervalId);
const randomIndex = Math.floor(Math.random() * cells.length);
highlightCell(randomIndex);
}
startButton.addEventListener('click', () => {
startLottery();
setTimeout(stopLottery, 3000); // 3秒后停止
});
通過以上步驟,我們實現了一個簡單的九宮格抽獎功能。這個功能可以進一步擴展,例如添加獎品信息、增加動畫效果等。希望本文對你理解如何使用原生JavaScript實現九宮格抽獎有所幫助。
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。