外面摆满了球,球上有字,拖动小球进入对应的框,如果答对则弹出对话框,写出相对应的代码
时间: 2023-10-03 21:11:01 浏览: 134
这个游戏的名称是“拖拽游戏”,下面是一个简单的实现,使用了HTML、CSS和JavaScript:
HTML代码:
```
<div class="container">
<div class="box" id="box1"></div>
<div class="box" id="box2"></div>
<div class="box" id="box3"></div>
<div class="ball" id="ball1" draggable="true">Apple</div>
<div class="ball" id="ball2" draggable="true">Banana</div>
<div class="ball" id="ball3" draggable="true">Orange</div>
</div>
```
CSS代码:
```
.container {
width: 600px;
height: 400px;
border: 2px solid #000;
position: relative;
}
.box {
width: 100px;
height: 100px;
border: 2px solid #000;
position: absolute;
top: 50%;
transform: translateY(-50%);
}
#box1 {
left: 10%;
}
#box2 {
left: 40%;
}
#box3 {
left: 70%;
}
.ball {
width: 80px;
height: 80px;
border-radius: 50%;
background-color: #999;
color: #fff;
text-align: center;
line-height: 80px;
position: absolute;
cursor: move;
}
```
JavaScript代码:
```
var ball1 = document.getElementById("ball1");
var ball2 = document.getElementById("ball2");
var ball3 = document.getElementById("ball3");
var box1 = document.getElementById("box1");
var box2 = document.getElementById("box2");
var box3 = document.getElementById("box3");
ball1.addEventListener("dragstart", drag);
ball2.addEventListener("dragstart", drag);
ball3.addEventListener("dragstart", drag);
box1.addEventListener("dragover", allowDrop);
box2.addEventListener("dragover", allowDrop);
box3.addEventListener("dragover", allowDrop);
box1.addEventListener("drop", drop);
box2.addEventListener("drop", drop);
box3.addEventListener("drop", drop);
function drag(e) {
e.dataTransfer.setData("text", e.target.id);
}
function allowDrop(e) {
e.preventDefault();
}
function drop(e) {
e.preventDefault();
var data = e.dataTransfer.getData("text");
var ball = document.getElementById(data);
var box = e.target;
if (box.id == "box1" && ball.innerHTML == "Apple") {
alert("Correct!");
} else if (box.id == "box2" && ball.innerHTML == "Banana") {
alert("Correct!");
} else if (box.id == "box3" && ball.innerHTML == "Orange") {
alert("Correct!");
} else {
alert("Incorrect!");
}
box.appendChild(ball);
}
```
您可以将以上代码复制粘贴到HTML、CSS和JavaScript文件中,并在浏览器中打开HTML文件来运行游戏。
阅读全文