html实现拖放的棋盘游戏
时间: 2024-01-05 08:19:47 浏览: 188
以下是一个使用HTML和JavaScript实现拖放的棋盘游戏的例子:
```html
<!DOCTYPE html>
<html>
<head>
<style>
.chessboard {
display: flex;
flex-wrap: wrap;
width: 400px;
height: 400px;
border: 1px solid black;
}
.square {
width: 50px;
height: 50px;
border: 1px solid black;
}
.piece {
width: 50px;
height: 50px;
background-color: red;
cursor: move;
}
</style>
</head>
<body>
<div class="chessboard">
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
<div class="square"></div>
</div>
<script>
var draggedPiece = null;
function handleDragStart(event) {
draggedPiece = event.target;
event.dataTransfer.setData('text/plain', null);
event.target.style.opacity = '0.5';
}
function handleDragEnd(event) {
event.target.style.opacity = '1';
}
function handleDragOver(event) {
event.preventDefault();
}
function handleDrop(event) {
event.preventDefault();
if (event.target.classList.contains('square')) {
event.target.appendChild(draggedPiece);
}
}
var pieces = document.getElementsByClassName('piece');
for (var i = 0; i < pieces.length; i++) {
pieces[i].addEventListener('dragstart', handleDragStart);
pieces[i].addEventListener('dragend', handleDragEnd);
}
var squares = document.getElementsByClassName('square');
for (var i = 0; i < squares.length; i++) {
squares[i].addEventListener('dragover', handleDragOver);
squares[i].addEventListener('drop', handleDrop);
}
</script>
</body>
</html>
```
这个例子创建了一个棋盘游戏的HTML页面。棋盘由一系列正方形的格子组成,每个格子都可以拖放棋子。棋子被表示为红色的方块,可以通过拖动它们来移动到其他格子上。当拖动棋子时,它的透明度会降低,当放下棋子时,它会被放置在目标格子中。
阅读全文