您的位置:首页 > Web前端 > JavaScript

javascript实现点击星星小游戏

2019-12-25 12:03 1566 查看

本文实例为大家分享了JavaScript实现点击星星的具体代码,供大家参考,具体内容如下

<head>
<meta charset="UTF-8">
<title>Document</title>
<style type="text/css">
#d2{
width:100px;
height:20px;
border:1px solid red;
display:inline-block;
}
#d3{
display:inline-block;
background:yellow;
height:20px;
}
</style>
<script type="text/javascript">
<!--
var dingshiqi; //定时器
var count=0; //记录星星的个数
var n=0; //记录游戏时间的变量。
var sj; //时间定时器(解决一直按开始游戏bug)
function StarGame(){ //开始游戏
window.clearInterval(sj); //清除时间定时器
window.clearInterval(dingshiqi);//清楚定时器
dingshiqi=window.setInterval("star()",400);
sj=window.setInterval("shijian()",1000);
}
//创建星星
function star(){
var obj=document.createElement("img");
//给星星添加src属性
obj.src="image.png"
//随机星星大小
var w=Math.floor(Math.random()*80+20);
obj.width=w;
obj.height=w;
//随机位置
var x=Math.floor(Math.random()*1166+100);
var y=Math.floor(Math.random()*500+100);
obj.style.position="absolute";
obj.style.top=y+"px";
obj.style.left=x+"px";
//放到body中
document.body.appendChild(obj);
//添加onclick点击事件(绑定的onclick 不需要加";")
obj.οnclick=removeStar;
//控制大于20个星星游戏结束
count++;
var sp=document.getElementById("d3");
sp.style.width=count*5+"px";
if(count>20){
alert("大于20个星星游戏结束");
window.clearInterval(dingshiqi);
location.reload(); //重新加载
}
//放到body中
document.body.appendChild(obj);
}
//点击删除星星
function removeStar(){
this.parentNode.removeChild(this);
count--; //点击星星删除,都要count-1.
var sp=document.getElementById("d3");
sp.style.width=count*5+"px";
}
//点击暂停游戏。
function zanting(){
alert("暂停游戏");
}
//记录游戏时间的函数
function shijian(){
n++;
var obj=document.getElementById("d1");
obj.innerHTML="游戏进行了"+n+"秒"
}
//-->
</script>
</head>
<body>
<input type="button" value="开始游戏" οnclick="StarGame()">
<input type="button" value="暂停游戏" οnclick="zanting()">
<span id="d1">游戏进行了0秒</span>
<span id="d2"><span id="d3"></span></span>
</body>
</html>

以上就是本文的全部内容,希望对大家的学习有所帮助

您可能感兴趣的文章:

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  js 点击星星