2048碰撞效果源码
时间: 2023-07-05 12:14:21 浏览: 33
以下是一个基于 HTML、CSS 和 JavaScript 的简单实现:
HTML 代码:
```
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>2048 碰撞效果</title>
<link rel="stylesheet" type="text/css" href="style.css">
</head>
<body>
<div class="container">
<div class="box">2</div>
<div class="box">2</div>
<div class="box">4</div>
<div class="box">8</div>
</div>
<script src="script.js"></script>
</body>
</html>
```
CSS 代码:
```
.container {
display: flex;
flex-wrap: wrap;
justify-content: space-between;
width: 400px;
}
.box {
align-items: center;
background-color: #eee4da;
border-radius: 6px;
display: flex;
font-size: 24px;
height: 100px;
justify-content: center;
margin-bottom: 16px;
margin-right: 16px;
width: 100px;
transition: all 0.2s ease-in-out;
}
.box.collide {
animation: collide 0.2s ease-in-out;
}
@keyframes collide {
0% {
transform: scale(1);
}
20% {
transform: scale(1.2);
}
40% {
transform: scale(0.8);
}
60% {
transform: scale(1.1);
}
80% {
transform: scale(0.9);
}
100% {
transform: scale(1);
}
}
```
JavaScript 代码:
```
const boxes = document.querySelectorAll('.box');
for (let i = 0; i < boxes.length; i++) {
boxes[i].addEventListener('click', function() {
const nextBox = boxes[i + 1];
if (nextBox && boxes[i].innerHTML === nextBox.innerHTML) {
boxes[i].classList.add('collide');
nextBox.classList.add('collide');
setTimeout(function() {
boxes[i].innerHTML = parseInt(boxes[i].innerHTML) * 2;
boxes[i].classList.remove('collide');
nextBox.parentNode.removeChild(nextBox);
}, 200);
}
});
}
```
这段代码使用了 flexbox 布局和 CSS 动画来实现碰撞效果。JavaScript 代码为每个方块添加了一个点击事件,当点击的方块与相邻的方块数字相同时,就会触发碰撞动画并合并两个方块。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)