[javascript]代码库
<!DOCTYPE html>
<html>
<head>
<style>
#background{
width:800px;
height:800px;
background: #EBEBEB;
position: absolute;
}
.mole{
width: 20px;
height: 20px;
background-image: xxx; /*这里可以找地鼠图片或者gif代替黑色圆圈*/
background: #000000;
border-radius: 50%;
position: absolute;
}
</style>
</head>
<body>
<h1>JavaScript打地鼠小游戏<h1>
<div style="height:50px;line-height:50px;text-align:center;margin-top:20px;">
当前得分:<span id="scores_show">0</span>
</div>
<div id="background"></div>
</body>
<script>
//1.创建指定范围内的随机数
function randomnum(min,max){
return Math.floor(Math.random()*(max-min+1)+min);
}
//2.让地鼠动起来
//2-1.创建一个div
function createDiv(){
var div=document.createElement('div');
div.setAttribute('class','mole');
div.style.left=randomnum(0,780)+"px";
div.style.top=randomnum(0,780)+"px";
document.getElementById('background').appendChild(div);
}
//2-2.改变div位置
function changeDiv(){
var div=document.getElementsByClassName('mole');
for(var i=0;i<div.length;i++){
div[i].style.left=randomnum(0,780)+"px";
div[i].style.top=randomnum(0,780)+"px";
}
}
//3.点击地鼠消失,显示分数
var scores=0;
function clickDiv(e){
document.getElementById('background').removeChild(e.target);
scores++;
document.getElementById('scores_show').innerText=scores;
}
createDiv();
//越来越多地鼠
setInterval(() => {
createDiv();
}, 2000);
//改变地鼠位置
setInterval(() => {
changeDiv();
}, 5000);
document.getElementById('background').onclick=(e)=>{
clickDiv(e);
}
</script>
</html>
[代码运行效果截图]