用html5/css/js写一个简单的九宫格拼图游戏,并且html5代码中要包含css和js的引用
时间: 2024-05-02 09:16:29 浏览: 96
js实现九宫格拼图小游戏
好的,以下是一个简单的九宫格拼图游戏的 HTML5/CSS/JS 代码:
HTML5:
```html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>九宫格拼图</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<div class="container">
<div class="piece" data-id="1"></div>
<div class="piece" data-id="2"></div>
<div class="piece" data-id="3"></div>
<div class="piece" data-id="4"></div>
<div class="piece" data-id="5"></div>
<div class="piece" data-id="6"></div>
<div class="piece" data-id="7"></div>
<div class="piece" data-id="8"></div>
<div class="piece" data-id="9"></div>
</div>
<script src="app.js"></script>
</body>
</html>
```
CSS:
```css
.container {
width: 300px;
height: 300px;
margin: 50px auto;
display: flex;
flex-wrap: wrap;
}
.piece {
width: 100px;
height: 100px;
box-sizing: border-box;
border: 2px solid #333;
background-color: #ccc;
cursor: pointer;
}
.piece:hover {
background-color: #ddd;
}
```
JS:
```js
window.onload = function() {
var pieces = document.querySelectorAll('.piece');
// 随机打乱拼图
for (var i = 0; i < pieces.length; i++) {
var randIndex = Math.floor(Math.random() * pieces.length);
pieces[randIndex].style.order = i;
}
// 点击移动拼图
for (var i = 0; i < pieces.length; i++) {
pieces[i].addEventListener('click', function() {
var currentPiece = this;
var currentOrder = currentPiece.style.order;
// 上
var upPiece = document.querySelector('.piece[style="order: ' + (parseInt(currentOrder) - 3) + ';"]');
if (upPiece && upPiece.style.order != 'undefined') {
currentPiece.style.order = upPiece.style.order;
upPiece.style.order = currentOrder;
}
// 下
var downPiece = document.querySelector('.piece[style="order: ' + (parseInt(currentOrder) + 3) + ';"]');
if (downPiece && downPiece.style.order != 'undefined') {
currentPiece.style.order = downPiece.style.order;
downPiece.style.order = currentOrder;
}
// 左
var leftPiece = document.querySelector('.piece[style="order: ' + (parseInt(currentOrder) - 1) + ';"]');
if (leftPiece && leftPiece.style.order != 'undefined' && parseInt(currentOrder) % 3 != 0) {
currentPiece.style.order = leftPiece.style.order;
leftPiece.style.order = currentOrder;
}
// 右
var rightPiece = document.querySelector('.piece[style="order: ' + (parseInt(currentOrder) + 1) + ';"]');
if (rightPiece && rightPiece.style.order != 'undefined' && (parseInt(currentOrder) + 1) % 3 != 0) {
currentPiece.style.order = rightPiece.style.order;
rightPiece.style.order = currentOrder;
}
});
}
};
```
其中,HTML5 中包含了 CSS 和 JS 的引用,分别是:
```html
<link rel="stylesheet" href="style.css">
<script src="app.js"></script>
```
希望能对您有所帮助!
阅读全文