学习了JS,自己写了一个关于小球撞墙的小练习,呈现的的效果是点击框里的空白会出现小球去撞红色的墙,墙后面有一个血槽,小球撞一下,血槽的血就少一格,当血槽里的血都消失时,墙消失.下面是具体实现的代码.
一.首先是body里的内容:创建一个大的div块,里面包含两个元素,是两个div快当作墙和血槽
<body>
<div id="wrap">
<div id="wall"></div>
<div id="blood"></div>
</div>
</body>
二.是css中的样式
*{
margin:0;
padding:0;
}
#wrap{
width:800px;
height:300px;
border:1px solid black;
position:relative;
margin: 50px auto;
}
#wall{
width:50px;
height:100px;
background:red;
position:absolute;
top:100px;
right:50px;
}
#blood{
width:10px;
height:100px;
border:1px solid black;
background:red;
box-sizing:border-box;
position:absolute;
top:100px;
right:30px;
}
#ball{
width:30px;
height:30px;
background:purple;
border-radius:50%;
position:absolute;
top:135px;
left:0;
}
.sblood{
width:10px;
height:10px;
background:red;
border:1px solid black;
box-sizing:border-box;
}
三.JS中的代码
<script type="text/javascript">
var wrap = document.getElementById(‘wrap‘);
var wall = document.getElementById(‘wall‘);
var blood = document.getElementById(‘blood‘);
补血
var sblood;
for(var i=0;i<10;i++){
sblood = document.createElement(‘div‘);
sblood.className = ‘sblood‘;
blood.appendChild(sblood);
}
wall.blood = 10;
创建小球
function createBall(){
var ball = document.createElement(‘div‘);
ball.id = ‘ball‘;
wrap.appendChild(ball);
var timer = null;
var offValue = ball.offsetLeft;
ball.move = function (){
timer = setInterval(function(){
offValue += 10;
ball.style.left = offValue+‘px‘;
判断是否撞墙
if (offValue >= wall.offsetLeft-ball.offsetWidth) {
wall.blood--;
if (wall.blood>=0) {
blood.childNodes[10-wall.blood-1].style.opacity = 0;
ball.clear();
}
if (wall.blood<=0) {
wall.remove();
blood.remove();
}
}
墙没有的时候才会撞到这
if (offValue >= wrap.offsetWidth-ball.offsetWidth) {
ball.clear();
}
},10);
}
ball.clear = function (){
ball.remove();
clearInterval(timer);
}
ball.move();
}
wrap.onclick = function(){
createBall();
}
</script>