原理实现比较简单,就是创建新的元素插入页面,然后做定时器处理就能实现
部分代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>打字母游戏</title>
<link rel="stylesheet" href="./css/index.css">
<script src="./js/jquery.min.js"></script>
</head>
<body>
<div class="box wrapper">
<img class="bg" src="./images/bg11.jpg" alt="">
<div class="zm"></div>
<div class="control">
<ul>
<li class="start"> <img src="./images/stop.png" alt=""><span class="txt">开始游戏</span></li>
<li class="add_speed"> <img src="./images/stop.png" alt=""><span class="txt">游戏加速</span></li>
<li class="stop"> <img src="./images/stop.png" alt=""><span class="txt">暂停游戏</span></li>
</ul>
</div>
<div class="score">
<img src="./images/fs.jpg" alt="">
<p>得分</p>
<span class="res_score">0</span>
</div>
</div>
<script>
$(function () {
let speedY = 50;
let score = 0;
let width = $('.box').width();
let height = $('.box').height();
let timer = null;
let flag = true;
$('.start').on('click',function () {
if (flag){
start();
}else{
flag = true;
start();
}
});
$('.stop').click(function () {
clearInterval(timer);
})
//开始移动,加速,得分
function start() {
clearInterval(timer);
timer = setInterval(function () {
createZm();
move($('.zm>li'));
},800);
//加速
$('.add_speed').click(function () {
speedY += 100;
});
$('.zm').on('click','li',function () {
score += 10;
$(this).remove();
changeScore();
});
}
//创建字母插入盒子中
function createZm() {
let zm = Math.floor(Math.random() * 26);
let url ='./images/'+ String.fromCharCode(65 + zm) + '.png';
let $li = $('<li><img src='+url+'></li>');
let x = Math.floor(Math.random() * width);
if (x + 100 > width) x -= 100;
if (x + 100 < 0) x = 100;
$li.css({
left: x + 'px'
})
$('.zm').prepend($li);
}
//移动所有字母
function move(lis) {
$.each(lis,function (index,value) {
let y = $(this).css('top');
y = parseInt(y.substring(0,y.length - 2));
if (speedY + y + $(this).height() * 1.4 <= height){
$(this).css({
top:speedY + y + 'px'
});
}else{
$(this).remove();
score -= 10;
changeScore();
}
})
}
function changeScore() {
$('.res_score').text(score);
}
})
</script>
</body>
</html>
支持一下
链接:百度网盘
提取码:6666