初学者js实现九宫格抽奖
时间: 2024-01-03 11:20:37 浏览: 91
原生JS实现九宫格抽奖
以下是初学者JS实现九宫格抽奖的代码示例:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>九宫格抽奖</title>
<style>
#box {
width: 300px;
height: 300px;
margin: 0 auto;
position: relative;
}
.cell {
width: 100px;
height: 100px;
position: absolute;
border: 1px solid #000;
box-sizing: border-box;
}
.cell span {
display: block;
width: 100%;
height: 100%;
line-height: 100px;
text-align: center;
font-size: 30px;
}
#start {
width: 100px;
height: 50px;
margin: 20px auto;
display: block;
font-size: 20px;
}
</style>
</head>
<body>
<div id="box">
<div class="cell" style="left: 0; top: 0;"><span>1</span></div>
<div class="cell" style="left: 100px; top: 0;"><span>2</span></div>
<div class="cell" style="left: 200px; top: 0;"><span>3</span></div>
<div class="cell" style="left: 200px; top: 100px;"><span>4</span></div>
<div class="cell" style="left: 200px; top: 200px;"><span>5</span></div>
<div class="cell" style="left: 100px; top: 200px;"><span>6</span></div>
<div class="cell" style="left: 0; top: 200px;"><span>7</span></div>
<div class="cell" style="left: 0; top: 100px;"><span>8</span></div>
<div class="cell" style="left: 100px; top: 100px;"><span>9</span></div>
</div>
<button id="start">开始</button>
<script>
var box = document.getElementById('box');
var cells = box.getElementsByClassName('cell');
var startBtn = document.getElementById('start');
var timer = null;
var index = 0;
var targetIndex = 0;
var isMoving = false;
// 点击开始按钮
startBtn.onclick = function() {
if (isMoving) {
return;
}
isMoving = true;
targetIndex = Math.floor(Math.random() * 9);
move();
}
// 移动单元格
function move() {
cells[index].style.borderColor = '#000';
index++;
if (index > 8) {
index = 0;
}
cells[index].style.borderColor = 'red';
if (index == targetIndex) {
clearInterval(timer);
isMoving = false;
}
}
// 定时器
timer = setInterval(move, 100);
</script>
</body>
</html>
```
阅读全文