用js+html+css写一个骰子
时间: 2023-04-02 13:02:10 浏览: 176
好的,我可以回答这个问题。以下是一个用 JavaScript、HTML 和 CSS 编写的骰子:
HTML 代码:
```
<div class="dice">
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
<div class="dot"></div>
</div>
```
CSS 代码:
```
.dice {
width: 100px;
height: 100px;
border: 1px solid black;
border-radius: 10px;
display: flex;
flex-wrap: wrap;
justify-content: space-between;
padding: 10px;
}
.dot {
width: 20px;
height: 20px;
border-radius: 50%;
background-color: black;
margin: 5px;
display: none;
}
.dot.active {
display: block;
}
@keyframes roll {
% {
transform: rotateX(deg) rotateY(deg) rotateZ(deg);
}
100% {
transform: rotateX(720deg) rotateY(720deg) rotateZ(720deg);
}
}
```
JavaScript 代码:
```
const dice = document.querySelector('.dice');
const dots = dice.querySelectorAll('.dot');
function rollDice() {
dice.classList.add('rolling');
setTimeout(() => {
dice.classList.remove('rolling');
const num = Math.floor(Math.random() * 6) + 1;
for (let i = ; i < dots.length; i++) {
dots[i].classList.remove('active');
}
switch (num) {
case 1:
dots[2].classList.add('active');
break;
case 2:
dots[].classList.add('active');
dots[4].classList.add('active');
break;
case 3:
dots[].classList.add('active');
dots[2].classList.add('active');
dots[4].classList.add('active');
break;
case 4:
dots[].classList.add('active');
dots[1].classList.add('active');
dots[3].classList.add('active');
dots[4].classList.add('active');
break;
case 5:
dots[].classList.add('active');
dots[1].classList.add('active');
dots[2].classList.add('active');
dots[3].classList.add('active');
dots[4].classList.add('active');
break;
case 6:
dots[].classList.add('active');
dots[1].classList.add('active');
dots[2].classList.add('active');
dots[3].classList.add('active');
dots[4].classList.add('active');
dots[5].classList.add('active');
break;
}
}, 200);
}
dice.addEventListener('click', rollDice);
```
这个骰子可以通过点击来掷骰子,每次掷骰子会随机出现 1 到 6 的数字。
阅读全文